Friday, August 11, 2006

SQL Chap 3 - Single Row Functions

Chapter 3 - Single-Row Functions
OCA/OCP: Introduction to Oracle9i SQL Study Guide
by Chip Dawes and Biju Thomas


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, 2002

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.
------

Double quotation marks must surround literal strings like "Week".
Ans: C


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 5 years
B. Employees hired within the past 5 days
C. Employees hired more than 5 years ago
D. Employees hired more than 5 days ago
-------
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.

Ans: D


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 the REGION_CODE is NULL, the first statement will not include that customer's PHONE_NUMBER.
B. If the 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 exception if the REGION_CODE is NULL for any customer.
-----
Ans: C. Both statements are equivalent.

Notes by Denis:
Only the functions CONCAT, DECODE, DUMP, NVL, NVL2, and REPLACE can return non-NULL values when called with a NULL argument.


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
----

Ans: B. INSTR returns a number. LPAD adds to a character string. LEAST does not change an input string.
INSTR - Finds the numeric starting position of a string within a string
LPAD - Left-fills a string to a set length using a specified character



5. The Sales department is simplifying the pricing policy for all products.
All surcharges are being incorporated into the base price for all products in the consumer division (code C),
and the new base price is increasing by the lesser of 0.5 percent of the old base price or
10 percent of the old surcharge. Using the PRODUCT table described below, you need to implement this change.


-----------------------------------------------------------
Column Name sku name division base_price surcharge
------------------------------------------------------------
Key Type pk
NULLs/Unique NN NN NN NN
FK Table
Datatype NUMBER VARCHAR2 VARCHAR2 NUMBER NUMBER
Length 16 16 4 11,2 11,2
-----------------------------------------------------------


Which of the following statements will achieve the desired results?


A.
UPDATE product SET
base_price = base_price + surcharge +
LEAST(base_price * 0.005
,surcharge * 0.1)
,surcharge = NULL
WHERE division='C'

B.
UPDATE product SET
base_price = base_price + NVL(surcharge,0) +
LEAST(base_price * 0.005
,surcharge * 0.1)
,surcharge = NULL
WHERE division='C'

C.
UPDATE product SET
base_price = base_price + NVL(surcharge,0) +
COALESCE(LEAST(base_price*0.005
,surcharge * 0.1)
,base_price * 0.005)
,surcharge = NULL
WHERE division='C'


D. A, B, and C will all achieve the desired results.
E. None of these statements will achieve the desired results.

----

Statements A and B do not account for NULL surcharges correctly and will set the base price to NULL where the surcharge is NULL. In statement C, the LEAST function will return a NULL if surcharge is NULL, in which case the BASE_PRICE * 0.005 would be added.
Ans:C

Notes by Denis:
COALESCE returns the first non-null expr in the expression list. At least one expr must not be the literal NULL. If all occurrences of expr evaluate to null, then the function returns null.


6. Which function(s) accept arguments of any datatype? (Choose all that apply.)

A. SUBSTR
B. NVL
C. ROUND
D. DECODE
E. SIGN

ROUND does not accept character arguments. SUBSTR accepts only character arguments. SIGN accepts only numeric arguments.
Ans: B, D


7. What will be returned by SIGN(ABS(NVL(-32,0)))?

A. 1
B. 32
C. -1
D. 0
E. NULL
----
Ans: A. The functions are evaluated from the innermost to outermost, as follows:
SIGN(ABS(NVL(-32,0))) = SIGN(ABS(-32)) = SIGN(32) = 1

Notes:
SIGN returns -1 if n<0. If n=0, then the function returns 0. If n>0, then SIGN returns 1.


8. One of your database users asked you to provide a command that will show her the NLS_DATE_FORMAT that is currently set in her session. Which command would you recommend?


A. SELECT SYS_CONTEXT('USERENV', 'NLS_DATE_FORMAT') FROM dual;
B. SELECT SYS_CONTEXT('NLS_DATE_FORMAT') FROM dual;
C. SELECT SYS_CONTEXT('NLS_DATE_FORMAT','USERENV') FROM dual;
D. SELECT NLS_DATE_FORMAT FROM dual;
----
The syntax for the SYS_CONTEXT function requires that the first argument be the namespace and the second argument be the parameter. There is no pseudo-column NLS_DATE_FORMAT, so it cannot be selected from DUAL.

Ans: A.


9. Which two functions could you use to strip leading characters from a character string?


A. LTRIM
B. SUBSTR
C. RTRIM
D. INSTR
E. MOD
----

Ans: A, B. RTRIM removes trailing (not leading) characters. The others return numbers.


10. You have been asked to randomly assign 25 percent of the employees to a new training program. Employee numbers are assigned as consecutive numbers to the employees. Which statement below will print the employee number and name of every fourth employee?


A.
SELECT MOD(empno, 4), ename
FROM employees
WHERE MOD(empno,4) = 0;

B.
SELECT empno, ename
FROM employees
WHERE MOD(empno, 4) = .25;

C.
SELECT MOD(empno, 4) ename
FROM employees
WHERE MOD(empno, 4) = 0;

D.
SELECT empno, ename
FROM employees
WHERE MOD(empno, 4) = 0;
-----

MOD returns the number remainder after division. Answers A and C don't return the employee number, and MOD(empno,4) won't return a decimal.

Ans: D.


11. Which function will convert the ASCII code 97 to its equivalent letter a?

A. ASC(97)
B. ASCIISTR(97)
C. ASCII(97)
D. CHR(97)
----
The CHR function converts an ASCII code to a letter. ASC does the inverse, converting a letter into its ASCII code. ASCIISTR converts a string to its ASCII equivalent. There is no ASCII function.
Ans: D.


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
----
The CURRENT_TIMESTAMP function returns the session date, session time, and session time zone offset.
Ans: A.


13. Using the SALESPERSON_REVENUE table described below, which statements will properly display the TOTAL_REVENUE (CAR_SALES + WARRANTY_SALES) of each salesperson?


--------------------------------------------------------
Column Name salesperson_id car_sales warranty_sales
--------------------------------------------------------
Key Type pk
NULLs/Unique NN NN
FK Table
Datatype NUMBER NUMBER NUMBER
Length 11,2 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;

-------

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.
Ans: C

14. Which function could be used to return the IP address for the machine where the client session connected from?

A. COOKIE
B. NETINFO
C. SYS_CONTEXT
D. SYS_CONNECT_BY_PATH
---

The COOKIE and NETINFO functions do not exist. The SYS_CONTEXT function returns session information, and one of the parameters in the USERENV namespace is IP_ADDRESS, which returns the IP address for the machine where the client connected from. The SYS_CONNECT_BY_PATH function is used for CONNECT BY (hierarchical) queries.
Ans: C


15. In Oracle, what do trigonometric functions operate on?


A. Degrees
B. Radians
C. Gradients
D. The default is radians, but degrees or gradients can be specified.
---

Oracle trigonometric functions operate only on radians.
Ans: B


16. What will the following SQL statement return?


SELECT COALESCE(NULL,'Oracle ','Certified') FROM dual;

A. NULL
B. Oracle
C. Certified
D. Oracle Certified
---

Ans: B. The COALESCE function returns the first non-NULL parameter, which is the character string 'Oracle '.


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')
-----

Option A will not work if there is a Feb 29 (leap year) in the next 365 days. Option B will always add one year to the present date. Option C will return the date one day later. NEW_TIME is used to return the date/time in a different time zone.
Ans: B.


18. Which function will return a TIMESTAMP WITH TIME ZONE datatype?

A. CURRENT_TIMESTAMP
B. LOCALTIMESTAMP
C. CURRENT_DATE
D. SYSDATE
----
LOCALTIMESTAMP does not return the time zone. CURRENT_DATE and SYSDATE return neither fractional seconds nor a time zone.
Ans: A.


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
----
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'.
Ans: D


20. Which function implements IF..THEN ELSE logic?


A. INITCAP()
B. REPLACE()
C. DECODE()
D. IFELSE()

------

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.
Ans: C

Average Number of Rows Per Data Block

(Note: Excerpt from a book that I can not remember)

Real World Scenario: How Can I Really Use SUBSTR?

A handy DBA use for SUBSTR is to count the average number of rows per data block in a table. Knowing the average number of rows per block will let you estimate disk space for that table.

A DBA frequently needs to estimate the disk space that a certain table will require. If you have a sample of a thousand or so rows of real data, you can load it, measure it, and accurately estimate the amount of disk space that will be required for the full data load. For example, if you know that an average of 100 rows fit in each 4KB data block, it becomes easy to estimate disk space for 1,000,000 rows as 1,000,000 rows / 100 rows per data block * 4KB per data block, which yields 40,000KB.

To count rows per data block, you need to use ROWIDs. ROWIDs have the format OOOOOOFFFBBBBBBRRR, where the Os represent the OID (object ID), the Fs represent the relative file number, the Bs the block number, and the Rs the row number within the block. You can count rows grouped on the O, F, and B parts of the ROWID (see Chapter 4 for more information on aggregate functions and grouping) to get the number of rows in each data block. This becomes the inline view or FROM subquery below (see Chapter 5, "Joins and Subqueries," for more information on subqueries). The main query then reports the minimum number of rows in a data block, the maximum number of rows in a data block, the average number of rows per data block, and the sum of all the rows in the table. (Note that if your table has chained rows, this technique will not properly count those chained blocks.)


SELECT MIN(cnt), MAX(cnt), AVG(cnt), SUM(cnt)
FROM (SELECT COUNT(*) cnt
FROM customer_orders
GROUP BY SUBSTR(ROWID,1,15));


MIN(CNT) MAX(CNT) AVG(CNT) SUM(CNT)

---------- ---------- ---------- ----------

60 332 202.145213 1446349

Thursday, August 10, 2006

SQL Chap 2 - SQL* Plus Overview


Chapter 2 - SQL*Plus Overview



OCA/OCP: Introduction to Oracle9i SQL Study Guide
by Chip Dawes and Biju Thomas


Review Questions

1. What is wrong with the following statements submitted in SQL*Plus?

DEFINE V_DEPTNO = 20
SELECT LAST_NAME, SALARY
FROM EMPLOYEES
WHERE DEPARTMENT_ID = V_DeptNo;

A. Nothing is wrong. The query lists the employee name and
salary of the employees who belong to department 20.
B. The DEFINE statement declaration is wrong.
C. The substitution variable is not preceded with the & character.
D. The substitution variable in the WHERE clause should be V_DEPTNO instead of V_DeptNo.
----

The query will return an error, because the substitution variable is used without
an ampersand (&) character. In this query, Oracle treats V_DEPTNO as another
column name from the table and returns an error. Substitution variables are
not case sensitive.

Ans: C


2. Which command in SQL*Plus is used to save the query output to a file?

A. PRINT
B. SAVE
C. REPLACE
D. SPOOL
----

The SPOOL command is used to save the query results to a file.
Issue SPOOL filename before the query and SPOOL OFF after the query to save
the contents. The SAVE command is used to save the SQL statement in the buffer.

Ans: D


3. How would you execute a SQL statement in the SQL buffer of SQL*Plus? (Choose all that apply.)


A. Enter a slash (/).
B. Enter an ampersand (&).
C. Enter a semicolon (;).
D. Press Ctrl+D (^D).
----

You can execute a statement in the SQL buffer using the slash. A semicolon will
just display the buffer again (similar to the LIST command).

Ans: A


4. You issue the SQL*Plus command SPOOL ON. Which task is accomplished?


A. The next screen output from the SQL*Plus session is saved into a file named afiedt.buf.
B. The next screen output from the SQL*Plus session is saved into a file named ON.lst.
C. The next screen output from the SQL*Plus session is sent to the printer.
D. Nothing happens; a filename is missing from the command.

----
The SPOOL command is used to save the SQL*Plus session output in a file. The SPOOL
command expects a filename or the keywords OUT or OFF. SPOOL OFF will turn off spooling;
SPOOL OUT will turn off spooling and send the output file contents to a printer.
If an extension is not specified for the filename, a default extension of .lst is added.

Ans: B


5. Which SQL*Plus command always overwrites a file?

A. SPOOL
B. RUN
C. REPLACE
D. SAVE

-----
The SPOOL command always creates a new file; it will not append to an existing file.
The SAVE command will give an error if the file exists. To overwrite an existing file,
you need to specify the REPLACE option with SAVE. REPLACE is not a valid command.

Ans: A


6. Which SQL*Plus command is used to display a title on every page of the report?


A. TOPTITLE
B. TITLE
C. TTITLE
D. REPTITLE

---
TTITLE is used to specify a title at the top of every page. A report title
at the beginning of the report can be specified using the REPHEADER command.

Ans: c


7. Choose two commands that are not valid in iSQL*Plus.


A. PASSWORD
B. TTITLE
C. CONNECT
D. EXIT
---

Certain SQL*Plus commands are not available in iSQL*Plus. Most of the unavailable
commands are not implemented because they are not relevant on a web interface.
Some commands are not implemented because they are not secure on the web server.

Ans: A, D.


8. Which character is used to indicate that the command is continued on the next line in SQL*Plus?


A. -
B. /
C. \
D. >

---
The continuation character in SQL*Plus is -. You do not need to use a continuation
character for SQL statements, but you need one for the SQL*Plus commands.
This is because SQL*Plus commands do not need to be terminated with ; or /,
whereas SQL statements have a terminator.

Ans: A


9. You have the following SQL in the SQL buffer of SQL*Plus:


SELECT EMPLOYEE_ID, LAST_NAME
FROM EMPLOYEES
WHERE LAST_NAME = FIRST_NAME
ORDER BY LAST_NAME

You perform the following SQL*Plus commands on the buffer:

3
c/NAME/NAMES/

Which SQL command will be in the buffer?

A.
SELECT EMPLOYEE_ID, LAST_NAMES
FROM EMPLOYEES
WHERE LAST_NAMES = FIRST_NAMES
ORDER BY LAST_NAMES

B.
SELECT EMPLOYEE_ID, LAST_NAME
FROM EMPLOYEES
WHERE LAST_NAMES = FIRST_NAME
ORDER BY LAST_NAME

C.
SELECT EMPLOYEE_ID, LAST_NAME
FROM EMPLOYEES
WHERE LAST_NAMES = FIRST_NAMES
ORDER BY LAST_NAME

D.
SELECT EMPLOYEE_ID, LAST_NAME
FROM EMPLOYEES
WHERE LAST_NAME = FIRST_NAME
ORDER BY LAST_NAME

----
The first SQL*Plus command, 3, makes the third line on the buffer as the current line.
The next command, c, changes the first occurrence of NAME to NAMES.

Ans: B


10. Which of the following is the correct syntax to define a variable?


A. DEFINE variable=value
B. DEFINE variable datatype := value
C. DEFINE &variable
D. DEFINE variable value
E. None of the above

----
To define a variable, you use the syntax DEFINE variable=value. The variable
will always be the CHAR datatype. To list the value of a variable, use DEFINE variable.

Ans: A


11. Which SET option turns off the display of the old and new SQL statement line when variables are used?


A. ECHO OFF
B. HEADING OFF
C. VERIFY OFF
D. FEEDBACK OFF
E. DEFINE OFF


----
SET VERIFY OFF will turn off the old and new line display when variables are used.
SET ECHO OFF turns off the display of SQL statements when running scripts.
SET HEADING OFF turns off the display of column headings.
SET FEEDBACK OFF turns off the feedback after executing each SQL statement.
SET DEFINE OFF turns off scanning for substitution variables in the SQL.

Ans: C


12. Which of the following is not a valid option with the SAVE command?


A. CREATE
B. REPLACE
C. APPEND
D. INSERT

---
The SAVE command is used to write the SQL buffer to a file. CREATE is the default
behavior; the file should not exist for this option to work. REPLACE overwrites the file.
APPEND adds the buffer to the end of the file if the file exists.
The same options are also valid for the STORE SET command,
which is used to save the SET environment to a file.

Ans: D


13. You execute the following lines of code in SQL*Plus:



SQL> SELECT department_id, first_name, salary
2 FROM employees
3 WHERE first_name LIKE 'S%'
4 ORDER BY department_id, first_name
5
SQL> COLUMN department_id FORMAT A20
SQL> C/department_id/employee_id


Which of the following best describes the code?

A. The department_id in the COLUMN command is replaced with employee_id.
B. The department_id in the COLUMN command is cleared (deleted).
C. The department_id in the fourth line of the SELECT statement is replaced with employee_id.
D. All the department_id occurrences in the SELECT statement are replaced with employee_id.

----
C is the abbreviation for CHANGE, which is a SQL buffer-editing command.
Only SQL statements are saved in the buffer; SQL*Plus commands are not saved.
Since the SELECT statement was the last SQL statement, the cursor stayed
in the last line of that statement. Therefore, the CHANGE command was applied on
the line beginning with the ORDER BY clause.

Ans: C


14. Which of the following is not a valid method for including comments?


A. Prefix comments with --.
B. Begin comment line with REMARK.
C. Begin comment line with #.
D. Include comments between /* and */.

----
Comments increase the readability of scripts. Comments using -- or /* */ can be
included anywhere in the SQL, but REMARK should be on a line of its own.
SQL*Plus ignores the rest of the line for REMARK and -- comments.

Ans: C


15. Consider the following SQL:


SELECT department_id, last_name, salary
FROM employees
ORDER BY department_id, last_name

Which SQL*Plus command(s) will display the total salary for each department and
suppress listing of duplicate department IDs?

A. COMPUTE SUM OF SALARY ON DEPARTMENT_ID
BREAK ON DEPARTMENT_ID

B. BREAK ON DEPARTMENT_ID NODUPLICATES
COMPUTE SUM ON SALARY FOR DEPARTMENT_ID

C. BREAK ON DEPARTMENT_ID NODUPLICATES -
SUM ON SALARY

D. None of the above. SQL*Plus cannot be used to total column values.


----
You need both the BREAK and COMPUTE commands to group values and perform an operation
(like sum or average). NODUPLICATES is the default behavior for the BREAK command.
You can optionally include a LABEL clause in the COMPUTE command to
replace the default column heading.

Ans: A.


16. When using iSQL*Plus, how do you write the query results to a file?


A. Use the SPOOL command to specify an output filename.
B. Use the Output drop-down button and select File.
C. Perform option A and B.
D. Perform either option A or B.

----
The SPOOL command is disabled in iSQL*Plus. You need to select the File option
from the Output drop-down list and specify a filename. Similarly, the Load Script
button can be used as the GET command, and the Clear Screen button can be used
as the CLEAR SCREEN command.

Ans: B


17. What will happen when you click the Execute button with the following SQL in iSQL*Plus?


SELECT employee_id, last_name, first_name
FROM employees
WHERE department_id = &deptid

A. Nothing will happen, because the statement is missing a ;.
B. An error is produced, because substitution variables are not allowed in iSQL*Plus.
C. A new window will be opened to accept the value for DEPTID.
D. The cursor moves to the string input area to accept value for DEPTID.
----

When substitution variables are used in iSQL*Plus, a new window will open to get the values for all variables before executing the SQL.

Ans: C


18. Which two statements regarding substitution variables are true?


A. &variable is defined by SQL*Plus, and its value will be available for the duration of the session.
B. &&variable is defined by SQL*Plus, and its value will be available for the duration of the session.
C. &n (where n is a any integer) variables are defined by SQL*Plus when values are passed
in as arguments to the script, and their values will be available for the duration of the session.
D. &&variable is defined by SQL*Plus, and its value will be available only for every reference
to that variable in the current SQL.

-----
When a variable is preceded by double ampersands, SQL*Plus defines that variable. Similarly,
when you pass values to a script using the START script_name arguments, SQL*Plus defines those variables.
Once a variable is defined, its value will be available for the duration of the session or
until you use UNDEFINE variable.

Ans: B, C


19. The contents of the script file MYSQL.sql are as follows:


SET PAGES 55 LINES 80 FEEDBACK OFF
SELECT last_name, first_name
FROM employees
WHERE employee_id = &empid;

What will happen when you issue the START MYSQL 101 command?

A. 101 will be substituted for the variable EMPID.
B. You will be prompted to enter a value for EMPID.
C. An error will be returned because EMPID is not preceded by &&.

----
You can pass values of substitution variables as parameters to a script only
when the substitution variables are defined as positional variables (&1, &2, and so on).

Ans: B


20. The EMP table is defined with the following columns:


EMPID NUMBER (5)
ENAME VARCHAR2 (30)
JOB_TITLE VARCHAR2 (30)

You execute the following SQL, and supply a value as shown.

SQL> SELECT * FROM EMP
2 WHERE ENAME = &name;
Enter value for name: John

What will be the result?

A. All the column values from the EMP table are displayed for the record with ENAME as John.
B. An error is returned, because John is a character literal and must be enclosed in quotation marks.
C. An error is returned, because Name is a reserved word in SQL*Plus, so it cannot be used as a variable.
D. The input value John will be converted to uppercase, and values from the EMP table are displayed for the record with ENAME as JOHN.

---
The WHERE clause of the query will become WHERE ENAME = John. Oracle will look
for a column named John in the EMP table and return an error. The character literal
must be enclosed in quotation marks. The WHERE clause should be written as
WHERE ENAME = '&NAME'.

Ans: B

SQL Chap 1 - Basic SQL SELECT Statements

Chapter 1 - Basic SQL SELECT Statements
OCA/OCP: Introduction to Oracle9i SQL Study Guide
by Chip Dawes and Biju Thomas


Review Questions

1. You issue the following query:
SELECT salary "Employee Salary"
FROM employees;


How will the column heading appear in the result?

A. EMPLOYEE SALARY
B. EMPLOYEE_SALARY
C. Employee Salary
D. employee_salary

Column alias names enclosed in quotation marks will appear as typed.
Spaces and mixed case appear in the column alias name only when
the alias is enclosed in double quotation marks.

Ans: C

2. The EMP table is defined as follows:

--------------------------
EMP Table
--------------------------
Column Datatype Length
--------------------------
EMPNO NUMBER 4
ENAME VARCHAR2 30
SALARY NUMBER 14,2
COMM NUMBER 10,2
DEPTNO NUMBER 2
--------------------------

You perform the following two queries:

SELECT empno enumber, ename
FROM emp ORDER BY 1;

SELECT empno, ename
FROM emp ORDER BY empno ASC;

Which of the following is true?

A. Statements 1 and 2 will produce the same result.
B. Statement 1 will execute; statement 2 will return an error.
C. Statement 2 will execute; statement 1 will return an error.
D. Statements 1 and 2 will execute but produce different results.

---
Statements 1 and 2 will produce the same result. You can use the column name,
column alias, or column position in the ORDER BY clause. The default sort
order is ascending. For a descending sort, you must explicitly specify
that order with the DESC keyword.

Ans: A

3. You issue the following SELECT statement on the EMP table shown in question 2.

SELECT (200+((salary*0.1)/2)) FROM emp;

What will happen to the result if all of the parentheses are removed?

A. No difference, because the answer will always be NULL.
B. No difference, because the result will be the same.
C. The result will be higher.
D. The result will be lower.
----
3.
In the arithmetic evaluation, multiplication and division have precedence
over addition and subtraction. Even if you do not include the parentheses,
salary*0.1 will be evaluated first. The result is then divided by 2,
and its result is added to 200.

Ans: B


4. In the following SELECT statement, which component is a literal?
(Choose all that apply.)
SELECT 'Employee Name: ' || ename
FROM emp where deptno = 10;


A. 10
B. ename
C. Employee Name:
D. ||
---

Character literals in the SQL statement are enclosed in single quotation marks.
Literals are concatenated using ||. Employee Name: is a character literal,
and 10 is a numeric literal.
Ans: A, C


5. When you try to save 34567.2255 into a column defined as NUMBER(7,2)
what value is actually saved?


A. 34567.00
B. 34567.23
C. 34567.22
D. 3456.22
-----

Since the numeric column is defined with precision 7 and scale 2, you can have
five digits in the integer part and two digits after the decimal point. The digits
after the decimal are rounded.

Ans: B


6. What is the default display length of the DATE datatype column?

A. 8
B. 9
C. 19
D. 6
----

The default display format of the DATE column is DD-MON-YY, whose length
is 9. This is U.S. specific and will be different as user settings vary.

Ans: B


7. What will happen if you query the EMP table shown in question 2 with the following?
SELECT empno, DISTINCT ename, salary FROM emp;


A. EMPNO, unique values of ENAME and then SALARY are displayed.
B. EMPNO, unique values of the two columns, ENAME and SALARY, are displayed.
C. DISTINCT is not a valid keyword in SQL.
D. No values will be displayed because the statement will return an error.
------

DISTINCT is used to display a unique result row, and it should follow immediately
after the keyword SELECT. Uniqueness is identified across the row, not a single column.

Ans: D


8. Which clause in a query limits the rows selected?


A. ORDER BY
B. WHERE
C. SELECT
D. FROM
-----

The WHERE clause is used to limit the rows returned from a query. The WHERE
clause condition is evaluated, and rows are returned only if the result is TRUE.
The ORDER BY clause is used to display the result in certain order.

Ans: B


9. The following listing shows the records of the EMP table.


EMPNO ENAME SALARY COMM DEPTNO
--------- ---------- --------- --------- ---------
7369 SMITH 800 20
7499 ALLEN 1600 300 30
7521 WARD 1250 500 30
7566 JONES 2975 20
7654 MARTIN 1250 1400 30
7698 BLAKE 2850 30
7782 CLARK 2450 24500 10
7788 SCOTT 3000 20
7839 KING 5000 50000 10
7844 TURNER 1500 0 30
7876 ADAMS 1100 20
7900 JAMES 950 30
7902 FORD 3000 20
7934 MILLER 1300 13000 10


When you issue the following query, which value will be displayed in the first row?

SELECT empno
FROM emp
WHERE deptno = 10
ORDER BY ename DESC;

A. MILLER
B. 7934
C. 7876
D. No rows will be returned because ename cannot be used in the ORDER BY clause.
------------


There are three records belonging to DEPTNO 10: EMPNO 7934 (MILLER), 7839 (KING),
and 7782 (CLARK). When you sort their names by descending order, MILLER is
the first row to display. You can use alias names and columns that are not in the
SELECT clause in the ORDER BY clause.

Ans: B

10. Refer to the listing of records in the EMP table in question 9.
How many rows will the following query return?


SELECT * FROM emp WHERE ename BETWEEN 'A' AND 'C'

A. 4
B. 2
C. A character column cannot be used in the BETWEEN operator.
D. 3
----

Here, a character column is compared against a string using the BETWEEN operator,
which is equivalent to ename >= 'A' AND ename <= 'C'. The name CLARK will
not be included in this query, because 'CLARK' is > 'C'.

Ans: D




11. Refer to the EMP table in question 2. When you issue the following query,
which line has an error?

SELECT empno "Enumber", ename "EmpName"
FROM emp
WHERE deptno = 10
AND "Enumber" = 7782
ORDER BY "Enumber";

A. 1
B. 5
C. 4
D. No error; the statement will finish successfully.
----

Column alias names cannot be used in the WHERE clause. They can be used in the ORDER BY clause.
Ans: C


12. You issue the following query:


SELECT empno, ename
FROM emp
WHERE empno = 7782 OR empno = 7876;

Which other operator can replace the OR condition in the WHERE clause?

A. IN
B. BETWEEN .. AND ..
C. LIKE
D. <=
E. >=
---

The IN operator can be used. You can write the WHERE clause as
WHERE empno IN (7782, 7876);
Ans: A


13. The following are clauses of the SELECT statement:

WHERE
FROM
ORDER BY

In which order should they appear in a query?

A. 1, 3, 2
B. 2, 1, 3
C. 2, 3, 1
D. The order of these clauses does not matter.
---


The FROM clause appears after the SELECT statement, followed by WHERE and
ORDER BY clauses. The FROM clause specifies the table names, the WHERE clause
limits the result set, and the ORDER BY clause sorts the result.

Ans: B


14. Which statement searches for PRODUCT_ID values that begin with DI_ from the ORDERS table?



A. SELECT * FROM ORDERS
WHERE PRODUCT_ID = 'DI%';

B. SELECT * FROM ORDERS
WHERE PRODUCT_ID LIKE 'DI_' ESCAPE '\';

C. SELECT * FROM ORDERS
WHERE PRODUCT_ID LIKE 'DI\_%' ESCAPE '\';

D. SELECT * FROM ORDERS
WHERE PRODUCT_ID LIKE 'DI\_' ESCAPE '\';

E. SELECT * FROM ORDERS
WHERE PRODUCT_ID LIKE 'DI_%' ESCAPE '\';


------
Since _ is a special pattern-matching character, you need to include the
ESCAPE clause in LIKE. The % character matches any number of characters including 0,
and _ matches a single character.

Ans: C


15. COUNTRY_NAME and REGION_ID are valid column names in the COUNTRIES table.
Which one of the following statements will execute without an error?


A.
SELECT country_name, region_id,
CASE region_id = 1 THEN 'Europe',
region_id = 2 THEN 'America',
region_id = 3 THEN 'Asia',
ELSE 'Other' END Continent
FROM countries;

B.
SELECT country_name, region_id,
CASE (region_id WHEN 1 THEN 'Europe',
WHEN 2 THEN 'America',
WHEN 3 THEN 'Asia',
ELSE 'Other') Continent
FROM countries;

C.
SELECT country_name, region_id,
CASE region_id WHEN 1 THEN 'Europe'
WHEN 2 THEN 'America'
WHEN 3 THEN 'Asia'
ELSE 'Other' END Continent
FROM countries;

D.
SELECT country_name, region_id,
CASE region_id WHEN 1 THEN 'Europe'
WHEN 2 THEN 'America'
WHEN 3 THEN 'Asia'
ELSE 'Other' Continent
FROM countries;


----
Ans: C. A CASE expression begins with the keyword CASE and ends with keyword END.


16. Which special character is used to query all the columns from the table without
listing each column by name?

A .%
B. &
C. @
D. *
------
Ans: D. An asterisk (*) is used to denote all columns in a table.

17. The EMPLOYEE table has the following data:



EMP_NAME HIRE_DATE SALARY
---------- --------- ----------
SMITH 17-DEC-90 800
ALLEN 20-FEB-91 1600
WARD 22-FEB-91 1250
JONES 02-APR-91 5975
WARDEN 28-SEP-91 1250
BLAKE 01-MAY-91 2850


What will be the value in the first row of the result set when the following query is executed?

SELECT hire_date FROM employee
ORDER BY salary, emp_name;

A. 02-APR-91
B. 17-DEC-90
C. 28-SEP-91
D. The query is invalid, because you cannot have a column in the
ORDER BY clause that is not part of the SELECT clause.
----

Ans: B. The default sorting order for numeric column is ascending. The columns
are sorted first by salary and then by name, so the row with the lowest salary is
displayed first. It is perfectly valid to use a column in the ORDER BY clause
that is not part of the SELECT clause.


18. Which SQL statement will query the EMPLOYEES table for FIRST_NAME, LAST_NAME,
and SALARY of all employees in DEPARTMENT_ID 40 in the alphabetical order of last name?

A.

SELECT first_name last_name salary
FROM employees
ORDER BY last_name
WHERE department_id = 40;

B.

SELECT first_name, last_name, salary
FROM employees
ORDER BY last_name ASC
WHERE department_id = 40;

C.

SELECT first_name last_name salary
FROM employees
WHERE department_id = 40
ORDER BY last_name ASC;

D.

SELECT first_name, last_name, salary
FROM employees
WHERE department_id = 40
ORDER BY last_name;

E.

SELECT first_name, last_name, salary
FROM TABLE employees
WHERE department_id IS 40
ORDER BY last_name ASC;

-------
In the SELECT clause, the column names should be separated by commas.
An alias name may be provided for each column with a space or using the keyword AS.
The FROM clause should appear after the SELECT clause. The WHERE clause appears
after the FROM clause. The ORDER BY clause comes after the WHERE clause.
Ans: D



19. When doing pattern matching using the LIKE operator, which character is used as
the default escape character by Oracle?


A. /
B. C. |
D. There is no default escape character in Oracle9i.
---

There is no default escape character in Oracle9i.
If your search includes pattern-matching characters such as _ or %, define an escape
character using the ESCAPE keyword in the LIKE operator.
Ans: D

20. Column alias names cannot be used in which clause?

A. SELECT clause
B. WHERE clause
C. ORDER BY clause
D. None of the above
------
Ans: B. Column alias names cannot be used in the WHERE clause of the SQL statement.
In the ORDER BY clause, you can use the column name or alias name, or indicate the
column by its position in the SELECT clause.

Tuesday, August 08, 2006

Introduction to Oracle 9i SQL - Assessment Test

1. Which operator will be evaluated first in the following SELECT statement?
SELECT (2+3*4/2-5) FROM dual;
A. +
B. *
C. /
D. -

Ans: B

2. Which line of the following code has an error?
SELECT *FROM emp WHERE comm = NULL ORDER BY ename;
A. SELECT *
B. FROM emp
C. WHERE comm = NULL
D. There is no error in this statement.

Ans. D.
Although there is no error in this statement, the statement will not return the desired result. When a NULL is compared, you cannot use the = or != operators; you must use the IS NULL or IS NOT NULL operator. See Chapter 1 for more information about the comparison operators.

3. Which two statements are true about NULL values?
A. You cannot search for a NULL value in a column using the WHERE clause.
B. If a NULL value is returned in the subquery or if NULL is included in the list when using a NOT IN operator, no rows will be returned.
C. Only = and != operators can be used to search for NULL values in a column.
D. In an ascending order sort, NULL values appear at the bottom of the result set.
E. Concatenating a NULL value to a non-NULL string results in a NULL.

Ans: B, D.
You can use the IS NULL or IS NOT NULL operator to search for NULLs or non-NULLs in a column. Since NULLs are sorted higher, they appear at the bottom of the result set in an ascending order sort.

4. Which components are required to run iSQL*Plus from your PC? (Choose all that apply.)
A. SQL*Plus installed on the PC
B. Oracle Net on the PC
C. HTTP Server
D. iSQL*Plus Server

Ans: C, D.
iSQL*Plus architecture includes three layers. The client layer is the web browser. The middle layer has the HTTP Server, iSQL*Plus server, and Oracle Net. The third layer is the Oracle database.

5. When you use the DEFINE variable command, what datatype is the variable?
A. VARCHAR2
B. CHAR
C. LONG
D. NUMBER
E. None of the above; you must specify the datatype along with the variable.

Ans: B.
Variables declared using the DEFINE command take the CHAR datatype. To assign a value to a variable, use DEFINE variable=value


6. Which function can return a non-NULL value if passed NULL arguments?
A. NULLIF
B. LENGTH
C. CONCAT
D. INSTR
E. TAN

Ans C.
CONCAT will return a non-NULL if only one parameter is NULL. Both CONCAT parameters would need to be NULL for CONCAT to return NULL. The NULLIF function returns NULL if the two parameters are equal. The LENGTH of a NULL is NULL. INSTR will return NULL if NULL is passed in, and the tangent of a NULL is NULL.

7. (skip)

8. The following statement will raise an exception on which line?
select dept_name, avg(all salary) ,count(*) "number of employees"
from emp , dept
where deptno = dept_no and count(*) > 5
group by dept_name
order by 2 desc;

A. select dept_name, avg(all salary), count(*) "number of employees"
B. where deptno = dept_no
C. and count(*) > 5
D. group by dept_name
E.order by 2 desc;

Ans C.
Group functions cannot appear in the WHERE clause.

9. Your HR department wants to recognize the most senior employees in each department. You need to produce a report with the following requirements:
Display each department ID
For each department, show the earliest hire date
Show how many employees from each department were hired on the earliest hire date
Will all three requirements be met with the following SQL statement?


select department_id ,min(hire_date) ,count(*) keep (dense_rank last order by hire_date asc)
from hr.employees
group by department_id;

A. The statement meets all three requirements.
B. The statement meets two of the three requirements.
C. The statement meets one of the three requirements.
D. The statement meets none of the three requirements.
E. The statement will raise an exception.


Ans B.
The first two columns (lines 1 and 2) will meet the first two requirements, but the third column (lines 3 and 4) will report the number of employees with the most recent hire date. To report the number of employees with the oldest hire date, you need either count(*) keep (dense_rank first order by hire_date asc) or count(*) keep (dense_rank last order by hire_date desc). See Chapter 4 for more information about group functions.

10. The DEPT table has the following data.
SQL> SELECT * FROM dept;
DEPTNO DNAME LOC
---------- -------------- ----------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Consider this INSERT statement:
INSERT INTO (SELECT * FROM dept WHERE deptno = 10)VALUES (50, 'MARKETING', 'FORT WORTH');

Choose the best answer.

A. The INSERT statement is invalid; a valid table name is missing.
B. 50 is not a valid DEPTNO value, since the subquery limits DEPTNO to 10.
C. The statement will work without error.
D. A subquery and a VALUES clause cannot appear together.

Ans C.
The statement will work without error. Option B would be correct if you used the WITH CHECK OPTION clause in the subquery. See Chapter 5 for more information about subqueries.

11. At a minimum, how many join conditions should there be to avoid a Cartesian join if there are three tables in the FROM clause?
A. 1
B. 2
C. 3
D. There is no minimum.


Ans: B.
There should be at least n-1 join conditions when joining n tables to avoid a Cartesian join. To learn more about joins, see Chapter 5.

12. Which two of the following queries is valid syntax that would return all rows from the EMPLOYEES and DEPARTMENTS tables, even if there are no corresponding/related rows in the other table.
A.
SELECT last_name, first_name, department_name FROM employees e FULL JOIN departments d ON e.department_id = d.department_id;
B. SELECT last_name, first_name, department_name FROM employees e OUTER JOIN departments d ON e.department_id = d.department_id;
C. SELECT e.last_name, e.first_name, d.department_name FROM employees e LEFT OUTER JOIN departments d ON e.department_id = d.department_id RIGHT OUTER JOIN employees f ON f.department_id = d.department_id;
D. SELECT e.last_name, e.first_name, d.department_nameFROM employees e CROSS JOIN departments d ON e.department_id = d.department_id;
E. SELECT last_name, first_name, department_name FROM employees FULL OUTER JOIN departments USING (department_id);

Ans: A, E.
An outer join on both tables can be achieved using the FULL OUTER JOIN syntax. The join condition can be specified using the ON clause to specify the columns explicitly or using the USING clause to specify columns with common column names. Options B and D would result in errors. In option B, the join type is not specified; OUTER is an optional keyword. In option D, CROSS JOIN is used to get a Cartesian result, and Oracle9i does not expect a join condition. To learn more about joins, read Chapter 5.

13. Why does the following statement fail?
CREATE TABLE FRUITS&VEGETABLES( NAME VARCHAR2 (40));
A. The table should have more than one column defined.
B. NAME is a reserved word, which cannot be used as a column name.
C. The table name is invalid.
D. Column length cannot exceed 30 characters.

Ans C. Table and column names can have only letters, numbers, and three special characters: dollar sign ($), underscore (_), and pound sign (#).

14. Which datatype stores data outside the Oracle database?
A. UROWID
B. BFILE
C. BLOB
D. NCLOB
E. EXTERNAL

Ans B.
The BFILE datatype stores only the locator to an external file in the database; the actual data is stored as operating system files. BLOB, NCLOB, CLOB, and BFILE are the LOB datatypes in Oracle9i. EXTERNAL is not a valid datatype.

15. Which of the following statements are true? (Choose all that apply.)
A. Primary key constraints allow NULL values in the columns.
B. Unique key constraints allow NULL values in the columns.
C. Primary key constraints do not allow NULL values in columns.
D. A nonunique index cannot be used to enforce a primary key
constraint.

Ans: B, C.
Primary key and unique key constraints can be enforced using nonunique indexes. Unique keys allow NULL values in the columns, but a primary key does not. See Chapter 7 for more information about constraints.

16. Which operation cannot be performed using the ALTER TABLE statement?
A. Rename table
B. Rename column
C. Drop column
D. Drop NOT NULL constraint

Ans:B.
You cannot rename a column in the table. To rename a column, you must re-create a table or create a view on the table with the new column name. See Chapter 7 for more information about modifying tables.

17. INTERVAL datatypes store a period of time. Which components are included in the INTERVAL DAY TO SECOND column? (Choose all that apply.)
A. Years
B. Quarters
C. Months
D. Days
E. Hours
F. Minutes
G. Seconds
H. Fractional seconds

Ans: D, E, F, G.
The INTERVAL DAY TO SECOND datatype is new to Oracle9i and is used to store an interval between two date/time components. See Chapter 7 for more information about Oracle9i datatypes.

18. Which of the following statements are true? (Choose all that apply.)
A. The TRUNCATE statement is used to selectively remove rows from table.
B. The TRUNCATE statement is used to remove all rows from a table.
C. Rows removed using the TRUNCATE command cannot be undone (rolled back).
D. The TRUNCATE statement drops the constraints and triggers associated with the table.
E. The TRUNCATE statement invalidates all the constraints and triggers associated with the table.

Ans: B, C.
You cannot specify a WHERE clause in the TRUNCATE statement; it removes all the rows in the table, releases the storage space (this is the default if you did not explicitly specify KEEP STORAGE), and does not drop or invalidate any of the dependent objects.

19. Which data dictionary view holds information about the columns in a view?
A. USER_VIEWS
B. USER_VIEW_COLUMNS
C. USER_TAB_COLUMNS
D. USER_ALL_COLUMNS

Ans C.
USER_VIEWS shows the SQL used to create the view. The view columns are in the USER_TAB_COLUMNS view. The view USER_UPDATABLE_COLUMNS will show the columns of the view that can be updated. See Chapter 8 for more information about views.


20. The primary key of the STATE table is STATE_CD. The primary key of the CITY table is STATE_CD and CITY_CD. The STATE_CD column of the CITY table is the foreign key to the STATE table. There are no other constraints on these two tables. Consider the following view definition.
CREATE OR REPLACE VIEW state_city
AS SELECT a.state_cd, a.state_name, b.city_cd, b.city_name
FROM state a, city b
WHERE a.state_cd = b.state_cd;

Which of the following operations are permitted on the base tables of the view? (Choose all that apply.)
A. Insert a record into the CITY table
B. Insert a record into the STATE table
C. Update the STATE_CD column of the CITY table
D. Update the CITY_CD column of the CITY table
E. Update the CITY_NAME column of the CITY table
F. Update the STATE_NAME column of the STATE table

Ans: D, E.
In the join view, CITY is the key-preserved table. You can update the columns of the CITY table, except STATE_CD, because STATE_CD is not part of the view definition (the STATE_CD column in the view is from the STATE table). Since we did not include the STATE_CD column from the CITY table, no INSERT operations are permitted (STATE_CD is part of the primary key). If the view were defined as follows, all the columns of the CITY table would have been updatable, and new records could be inserted into the CITY table.

CREATE OR REPLACE VIEW state_city AS
SELECT b.state_cd, a.state_name, b.city_cd, b.city_name
FROM states a, cities b
WHERE a.state_cd = b.state_cd;
See Chapter 8 for more information about views.

Note by Denis:
This question seems missing a condition. That is the operations are performed through the view.

A table in the join view is key-preserved, if the primary and unique keys of the table are unique on the view's result set.

21. In Oracle9i, outer join syntax can be specified using the LEFT JOIN or RIGHT JOIN keywords or by using the (+) operator. Suppose that you have the two tables PRODUCTS and ORDERS. You need to get the ORDER# and PRODUCT# for all orders, even if there is no order placed for a particular product; that is, you want to get all of the rows from the PRODUCTS table. The PRODUCT# column is common to both tables. Which condition would return the desired result?
A. WHERE PRODUCTS.PRODUCT# = ORDERS.PRODUCT#
B. WHERE PRODUCTS.PRODUCT# (+) = ORDERS.PRODUCT#
C. WHERE PRODUCTS.PRODUCT# = ORDERS.PRODUCT# (+)
D. WHERE PRODUCTS.PRODUCT# (+) = ORDERS.PRODUCT# (+)

A (+) is specified after the column name of the table where there may not be a corresponding row. Since we want to get all rows from the PRODUCTS table, the outer-join operator is placed beside the column names of the ORDERS table. See Chapter 5 for more information about joins.
Ans: C.
---

22. Oracle9i supports the ISO SQL99 standard for specifying joins in queries. Which keywords are used to specify a Cartesian join using this syntax?
A. NATURAL JOIN
B. OUTER JOIN
C. INNER JOIN
D. CROSS JOIN

CROSS JOIN specifies a Cartesian join. A Cartesian join occurs when you do not have a common column to join two tables. All combinations of all rows from both tables will be retrieved. If Table A has m rows and Table B has n rows, a Cartesian join would retrieve m × n rows. See Chapter 5 for more information about Cartesian joins.

Ans: D
------

23. Outer joins in Oracle9i can be specified using the syntax

Which keyword is optional?
A. JOIN
B. OUTER
C. JOIN and OUTER
D. None

In specifying joins using SQL 1999 syntax, the OUTER and INNER keywords are optional. See Chapter 5 for more information about the ISO SQL99 syntax for joins.

Ans: B

-------

24. The ORDERS table contains the following data:

select order_mode, sum(order_total)

from oe.orders

group by order_mode;

ORDER_MO SUM(ORDER_TOTAL)

-------- ----------------

direct 1903629.2

online 1764425.5

How much revenue will be inserted into the DIRECT_ORDERS table with the following SQL statement?

INSERT ALL

WHEN order_mode='online'

THEN INTO online_orders (customer_id, sales_rep_id, order_total) VALUES (customer_id, sales_rep_id, order_total)

WHEN order_mode ='direct'

THEN INTO direct_orders (customer_id, sales_rep_id, order_total) VALUES (customer_id, sales_rep_id, order_total)

WHEN order_mode in ('online','direct') THEN INTO direct_orders (customer_id, sales_rep_id, order_total) VALUES (customer_id, sales_rep_id, order_total)

SELECT order_mode, customer_id, sales_rep_id, order_total

FROM orders;

A. 3668054.7
B. 1903629.2
C. 1764425.5
D. 5571683.9

The ALL clause tells Oracle to execute each and every WHEN clause it evaluates to TRUE. Two of the three WHEN clauses evaluate to TRUE. So, the DIRECT_ORDERS rows are inserted twice: in the second and third WHEN clause. Additionally, the ONLINE_ORDERS would be inserted in the third WHEN clause into the DIRECT_SALES table. To pass the certification exam, you must understand how to correctly interpret SQL to both identify problems and satisfy requirements. See Chapter 6 for more information about the INSERT statement.

Ans D.

25. With regard to the following SQL statements, which of the following options is most correct?

UPDATE emp
SET salary = salary * 1.10
WHERE class_code = 'A';
SAVEPOINT ClassA_Floor Adjusted;

UPDATE emp
SET salary = salary * 1.07
WHERE class_code = 'B';
SAVEPOINT ClassB_FloorAdjusted;

UPDATE emp SET salary = salary * 1.05
WHERE class_code = 'C';
SAVEPOINT ClassC_FloorAdjusted;
ROLLBACK TO SAVEPOINT ClassB_FloorAdjusted;

UPDATE taxes SET max_tax = 76200*0.075
WHERE tax_type = 'FICA';
SAVEPOINT MaxTax;
ROLLBACK to MaxTax;
ROLLBACK to ClassA_FloorAdjusted;
COMMIT;



A. No changes occur to the EMP table, but the TAXES table is changed.
B. Both the EMP and TAXES tables are changed.
C. Only EMP rows with CLASS_CODE equal to 'A' are changed.
D. Only EMP rows with CLASS_CODES equal to 'C' are changed.
E. No changes occur to either the EMP or the TAXES table.

Only CLASS_CODE 'A' EMP rows are changed. The furthest we roll back is to the savepoint named ClassA_FloorAdjusted, so the only changes that are committed are those occurring before this savepoint (CLASS_CODE 'A') or after the rollback to savepoint (nothing). Chapter 6 discusses savepoints and rollbacks.

Ans: C

-----------


26. You need to change employees in department 50 who have a job ID of 'ST_CLERK' to department 80 and to manager ID 145. Which option will best satisfy these requirements?


A. update employees set department_id = 80 and manager_id = 145
where department_id = 50 and job_id = 'ST_CLERK';
B. update employees set (department_id, manager_id) = (80, 145)
where department_id = 50 and job_id = 'ST_CLERK';
C. update employees set department_id = 80,manager_id = 145
where department_id = 50 and job_id = 'ST_CLERK';
D. You need to use two UPDATE statements:
one for DEPARTMENT_ID and one for MANAGER_ID.

You can update multiple columns in a single UPDATE statement. The correct syntax to use when setting the columns to explicit values is to comma delimit each column = value clause. See Chapter 6 for more information on changing data with an UPDATE statement.
Ans: C.


27. The Marketing department has produced a master list of promotions for next month and placed it in table named NEW_PROMOTIONS. Some promotions are new and some have a new end date. You need to apply these promotions to the PROMOTIONS table using primary key PROMOTION_ID. Which statement best satisfies these requirements?

A.
update promotions p set promo_end_date =
(select promo_end_date from new_promotions np
where np.promo_id = p.promo_id);

B.
merge into promotions p using
select promo_id, end_date from new_promotions) np
on (p.promo_id = np.promo_id)
when matched then update
set p.end_date = np.end_date
when not matched then
insert (select promo_id, end_date)
values (np.promo_id, np.end_date);

C
upsert promotions p with new_promotions np
on (p.promo_id = np.promo_id)
when matched then update
set p.end_date = np.end_date
when not matched then insert(select promo_id, end_date)
values (np.promo_id, np.end_date);

D.
merge into promotions p using
(select promo_id, end_date from new_promotions) np
on (p.promo_id = np.promo_id)
if joined then update set p.end_date = np.end_date
else insert(select promo_id, end_date)
values (np.promo_id, np.end_date);

Option A will only update existing promotions, missing the new promotions. UPSERT appeared in marketing announcements of new Oracle9i features that are implemented via a MERGE statement. The correct syntax for the MERGE statement does not use an IF JOINED and ELSE construct; it uses a WHEN MATCHED and WHEN NOT MATCHED construct. See Chapter 6 for more information about modifying data with the MERGE statement.

Ans: B

28. What order does Oracle use in resolving a table or view referenced in a SQL statement?

A. Table/view within user's schema, public synonym, private synonym
B. Table/view within user's schema, private synonym, public synonym
C. Public synonym, table/view within user's schema, private synonym
D. Private synonym, public synonym, table/view within user's schema


Ans: B. Private synonyms override public synonyms, and tables or views owned by the user always resolve first. To learn more about synonyms, see Chapter 9.


29. Which statement will assign the next number from the sequence EMP_SEQ to the variable EMP_KEY?

A. emp_key := emp_seq.nextval;
B. emp_key := emp_seq.next_val;
C. emp_key := emp_seq.nextvalue;
D. emp_key := emp_seq.next_value;


Ans: A. This kind of question, which quizzes you on the precise syntax, really does appear on the exam. You'll need to know the correct spelling for sequence assignments. You can read about sequences in Chapter 9.

30. The table WKSYS.WK$CRAWLER_STAT has a B-tree index on the three columns WK$ITD, ID, and STAT_NAME. Which of the following statements could benefit from this index?
A. insert into wk$crawler_stat values (12,25,'timeout',NULL);
B. delete from wh$crawler_stat where id = 25;
C. select * from wk$crawler_stat where wk$itd between 2 and 12;
D. select * from wk$crawler_stat where id = 25 or stat_name like 'cache%';

Ans: C.

Indexes cannot improve the performance of INSERT statements. B-tree indexes can be used if a leading subset of columns is specified. A leading subset of columns for this index would need to include WK$ITD and optionally ID. Options B and D do not reference a leading subset of columns in the index. Option C is the only statement that references WK$ITD or a leading subset of indexed columns. You can read about indexes in Chapter 9.


31. Which of the following statements could use an index on the columns PRODUCT_ID and WAREHOUSE_ID of the OE.INVENTORIES table?
A. select count (distinct warehouse_id) from oe.inventories;
B. select product_id, quantity_on_hand from oe.inventories where warehouse_id = 100;
C. insert into oe.inventories values (5,100,32);
D. None of these statements could use the index

The index contains all the information needed to satisfy the query in option A, and a full-index scan would be faster than a full-table scan. A leading subset of indexes columns is not specified in the WHERE clause of option B, and INSERT operations, as in option C, are slowed down by indexes. For more information on indexes, see Chapter 9.

Ans: A.

32. Which one of the following statements will succeed?
A. grant create user, alter user to Katrina with admin option;

B. grant grant any privilege to Katrina with grant option;

C. grant create user, alter user to Katrina with grant option;

D. grant revoke any privilege to Katrina with admin option;

Ans: A. The grant option cannot be used on system privileges, and revoke any privilege is not a valid privilege. For more information on privileges, see Chapter 10.

33. What does the following statement do?
alter user effie identified by kerberos;
A. Creates user account effie
B. Changes the external authentication service for user effie
C. Makes effie a globally identified account
D. Changes user effie's password

Ans: D. Option A would be possible in Oracle6, but the exam is on Oracle9i. The kerberos password is just there to obfuscate. Chapter 10 discusses authentication and user accounts.

34. Which of the following system privileges cannot be granted to a role?
A. BECOME USER
B. UNLIMITED TABLESPACE
C. GRANT ANY ROLE
D. GRANT ANY PRIVILEGE

Ans: B.

UNLIMITED TABLESPACE is a special system privilege that must be granted to a user. BECOME USER is used for full database imports and comes standard as part of the IMP_FULL_DATABASE role. GRANT ANY ROLE and GRANT ANY PRIVILEGE have no restrictions on the grantee. Chapter 10 discusses system privileges and their restrictions.

35. User Rob granted SELECT on table OUTLN.OL$ to Chip WITH GRANT OPTION, and Chip has granted SELECT on OUTLN.OL$ to Ernie. Rob has also granted the DBA role to Chip WITH ADMIN OPTION, and Chip has granted DBA to Ernie. Chip leaves the department, and his account is dropped. Which privileges will Ernie still have if no other privileges are granted?

A. Both SELECT on table OUTLN.OL$ and DBA
B. Neither privilege
C. Only SELECT on table OUTLN.OL$
D. Only DBA

Ans: D. Revocations of object privileges cascade, but system and role privilege revocations do not. The DBA role will remain after user Chip is dropped, but the object privilege SELECT on OUTLN.OL$ that Chip granted will be dropped when user Chip is dropped. For more information on database privileges, see Chapter 10.