You are on page 1of 164

PL/SQL Fundamental Exam Answers

NOTE: The answers go with their sequences. If a question was not answer, that means
that it a repeating question and the answer was given by the previous questions or it is not
in the scope of this subject.

“Watch your thoughts; they become words. Watch your words; they become
actions. Watch your actions; they become habits. Watch your habits; they
become character. Watch your character; it becomes your destiny.”

--Frank Outlaw
Answers:
Q: What is PL/SQL?
A: PL/SQL is a language that was provided by Oracle.

Q: Where can you store a PL/SQL procedure?


A: It can be stored on the Oracle database (server side) or in a library that was created in
the users’ PC (client side).

Q: What is the PL/SQL body section?


A: It is a section that executes PL/SQL statements.

Q: What is the PL/SQL declaration section?


A: It is a section that you can declare the stored procedure’s variables.

Q: What does the SET SERVEROUTPUT command?


A: We use the SET SERVEROUTPUT command to display the content of the Oracle
buffer into our screen.

Q: What does the DBMS_OUTPUT.PUT_LINE procedure?


A: The DBMS_OUTPUT.PUT_LINE procedure writes the passing string into the
Oracle buffer.

Q: How do you define a variable or variables in the PL/SQL declaration section?


A: SQL> DECLARE
v_dname VARCHAR2(14);
BEGIN
v_dname := 'HR';
dbms_output.put_line(v_dname);
END;
/

Q: How do you save a PL/SQL block in the client environment?


A: There are so many ways. But one way is:
SQL> SAVE c:\iself\test_myblock.sql

Q: How do you use the %TYPE keyword?


A: v_dname dept.dname%TYPE;
We use the %type keyword, to declare the v_dname variable as the same datatype and
size of the department name
column of the dept table.

Q: How do you open a saved PL/SQL block?


A: SQL> GET c:\iself\test_myblock.sql

Q: How do you run a saved PL/SQL block?


A: SQL> run c:\iself\test_myblock.sql

Q: What does the %ROWTYPE keyword in the PL/SQL language?


A: The %ROWTYPE keyword creates a composite datatype in which all the columns of
a row are
pieced together into a record.

Q: What is an implicit cursor in the PL/SQL language?


A: If we define our cursor in the PL/SQL body, it will be called an implicit cursor.

Q: An implicit cursor must have _________ on its SELECT SQL statement?


A: INTO

Q: What does the SQL%NOTFOUND reserved PL/SQL word?


A: The SQL%NOTFOUND reserved word returns the FALSE value if there are
records to read from cursor and returns the TRUE value if there are not record exist to
read from cursor.

Q: What does the “SET SERVEROUTPUT ON?”


A: It displays the Oracle buffer used by the DBMS_OUTPUT package.

Q: Write a PL/SQL block, to output the "Hello iSelfSchooling" message.


A: SQL> BEGIN
dbms_output.put_line('Hello iselfschooling');
END;
/

Q: Use the %TYPE keyword, to declare a variable as the same datatype and size of the
department name column of the dept table.
A: DECLARE
v_dname dept.dname%TYPE;
BEGIN
v_dname := 'HR';
dbms_output.put_line(v_dname);
END;
/

Q: Use the implicit cursor to query the department table information where deptno is
30.
Check, if no record was found then print “Record was not found.” Else print the
department name only.
A: DECLARE
V_DREC DEPT%ROWTYPE;
BEGIN
SELECT * INTO V_DREC
FROM DEPT
WHERE DEPTNO = 30;
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('RECORD WAS NOT FOUND.');
ELSE
DBSM_OUTPUT.PUT_LINE(V_DREC.DNAME);
END IF;
END;
/

Q: Describe that why do we need to use a solid naming convention in our PL/SQL
program.
A: Easy to read.

Q: What is the explicit cursor in the PL/SQL language?


A: It is a cursor that was declared in the PL/SQL declaration section and returns more
than one records.

Q: What are the differences between the explicit and implicit cursors?
A:
1- Explicit cursor will be defined in the declaration section but implicit cursor will
be defined in the execution or body section.
2- The implicit cursor must have INTO clause in its SQL statement.
3- The explicit cursor can return more than one record but the implicit cursor should
only return one and only one record.

Q: Where do you declare an explicit cursor in the PL/SQL language?


A: In the PL/SQL declaration section.

Q: Where do you declare an implicit cursor in the PL/SQL language?


A: In the PL/SQL body section.

Q: What is a simple loop in the PL/SQL language?


A: It is a loop that we must program our exit from the loop. We must make sure that we
don’t get in an infinite loop.
Q: How do you open an explicit cursor in the PL/SQL language?
A: OPEN CURSOR_NAME;

Q: What does the FETCH statement in the Oracle PL/SQL language?


A: It reads one record at a time.

Q: How do you terminate from a simple loop in the PL/SQL language?


A: EXIT WHEN condition2exit;

Q: How do you OPEN or CLOSE a cursor in the PL/SQL language?


A: OPEN CURSOR_NAME;
CLOSE CURSOR_NAME;

Q: Declare a cursor to list the department name (dname), total number of employees
(ttemp), total salary (ttsal), and average salary (avsal) for each department from the
department table and employee table order by the department name.
Write all department name with their total number of employees for each department
using the notepad editor.

For example: ACCOUNTING has 3 employees.


(Note: Don’t use the ttemp, ttsal, and avsal item at this time)
A: DECLARE
-- DECLARE A VARIABLE FOR A CURSOR.
TYPE T_DS IS RECORD (
DNAME DEPT.DNAME%TYPE,
TTEMP NUMBER(3),
TTSAL NUMBER(8,2),
AVSAL NUMBER(8,2));

-- DEFINE DEPARTMENT STATISTICS


CURSOR C_DS IS
SELECT DNAME, COUNT (*) TTEMP,
SUM(SAL) TTSAL, AVG(SAL) AVSAL
FROM DEPT D, EMP E
WHERE D.DEPTNO = E.DEPTNO
GROUP BY DNAME
ORDER BY 1;

-- DEFINE A VARIABLE FOR CURSOR


V_DS T_DS;
BEGIN
-- OPEN THE CURSOR
OPEN C_DS;
-- START LOOP
LOOP
--READ A RECORD
FETCH C_DS INTO V_DS;
-- EXIT FROM LOOP
EXIT WHEN c_ds%notfound;
-- LIST DEPT. NAME
DBMS_OUTPUT.PUT_LINE
(V_DS.DNAME ||
‘ HAS ’ || V_DS.TTEMP || ‘ EMPLOYEES.’);
-- END THE LOOP
END LOOP;
CLOSE C_DS;
END;
/

Q: What does the FOR LOOP statement in the PL/SQL language?


A: It is a loop statement.

Q: What are the differences between a SIMPLE LOOP and FOR LOOP?
A: We don’t need to use the OPEN, CLOSE, FETCH, and EXIT PL/SQL statements,
and also to declare a cursor variable since the “FOR LOOP” statement does them
implicitly.

Q: What are the advantages of using the FOR LOOP statement?


A: It is very simple to write.

Q: What does the SHOW ERRORS statement in the PL/SQL language?


A: It displays the last existing PL/SQL errors that was compiled.

Q: What is the IF-THEN-ELSE statement?


A: It is an example of controlling process flow.

Q: Modify the previous PL/SQL block and use the “FOR LOOP” statement vs the
simple “LOOP” statement. Also, list only the department name that their total number of
employees is more than 4.
A: DECLARE
CURSOR c_ds IS
SELECT dname, count (*) ttemp,
sum(sal) ttsal, avg(sal) avsal
FROM dept d, emp e
WHERE d.deptno = e.deptno
GROUP BY dname ORDER BY 1;
BEGIN
-- for loop to read cursor record.
FOR v_ds IN c_ds LOOP
IF v_ds.ttemp > 4 THEN
DBMS_OUTPUT.PUT_LINE
(v_ds.dname || ‘ has ’ || v_ds.ttemp || ‘ employees.’);
END IF;
END LOOP;
END;
/

Q: Create a table named "dept_stat". The table should have four columns: department
name (dname), total number of employees (total_empno), total salary of employees
(total_sal), and average salary of employees (avg_sal). And the department name should
be a primary key. The following are its columns, datatypes and index constraint:
dname VARCHAR2(20) primary key
total_empno NUMBER(3)
total_sal NUMBER (8,2)
avg_sal NUMBER (8,2)
A: SQL> CREATE TABLE dept_stat
(dname VARCHAR2(20) primary key,
total_empno NUMBER(3),
total_sal NUMBER (8,2),
avg_sal NUMBER (8,2));

Q: Write a PL/SQL block to populate the department table statistics into the “dept_stat”
table.
Statistics Information:
The Department Number,
The total number of employees in each department,
The total salary paid in each department, and
The average salary paid in each department.
A:
DECLARE
-- define department statistics
cursor c_ds is
SELECT dname, count (*) ttemp,
SUM(sal) ttsal, AVG(sal) avsal
FROM dept d, emp e
WHERE d.deptno = e.deptno
GROUP BY dname;
BEGIN
-- loop to read cursor record.
FOR v_ds IN c_ds LOOP
-- insert into dept_stat
insert into dept_stat
values (v_ds.dname, v_ds.ttemp,
v_ds.ttsal, v_ds.avsal);
END LOOP;
-- save the insert transaction.
commit;
END;
/

Q: What is the cursor parameter in the PL/SQL language?


A: It is a parameter that we pass to a cursor.

Q: Where do you define a cursor parameter in the PL/SQL language?


A: In the PL/SQL CURSOR statement in the PL/SQL declaration section.

Q: Write a PL/SQL block to populate the department table statistics into the “dept_stat”
table for a specific department.
Statistics Information:
The Department Number,
The total number of employees in each department,
The total salary paid in each department, and
The average salary paid in each department.
A: >> DECLARE
-- DEFINE DEPARTMENT STATISTICS
CURSOR C_DS (P_DEPTNO DEPT.DEPTNO%TYPE) IS
SELECT DNAME, COUNT (*) TTEMP,
SUM(SAL) TTSAL, AVG(SAL) AVSAL
FROM DEPT D, EMP E
WHERE D.DEPTNO = E.DEPTNO
AND D.DEPTNO = P_DEPTNO
GROUP BY DNAME;
-- DEFINE DEPTNO VARIABLE
V_DEPTNO NUMBER(2);
BEGIN
-- ASSIGN DEPTNO 10
V_DEPTNO := 10;
-- LOOP TO READ CURSOR RECORD.
FOR V_DS IN C_DS (V_DEPTNO) LOOP
-- INSERT INTO DEPT_STAT
INSERT INTO DEPT_STAT
VALUES (V_DS.DNAME, V_DS.TTEMP,
V_DS.TTSAL, V_DS.AVSAL);
END LOOP;
-- save the insert transaction.
COMMIT;
END;
/

Q: What is the EXCEPTION section in the PL/SQL language?


A: The PL/SQL EXCEPTION section is a place that handles your errors that occurs
in the execution time.
Q: What do you use the EXCEPTION section for?
A: For stored procedure’s error handling.

Q: What would be happen if you don’t define your exception in the PL/SQL procedure?
A: If there is an execution error, then it will crash. It crashes since the program didn’t
know how
to handle the errors.

Q: What is an Oracle Defined EXCEPTION?


A: They are those exceptions that were defined by Oracle.

Q: What is a User Defined EXCEPTION?


A: They are those exceptions that were defined by developers.

Q: What are the differences between a User Defined and an Oracle defined exceptions?
A: The user defined exception needs to be declared and checked in the PL/SQL body
section.

Q: Modify the previous PL/SQL block--last assignment in the previous hands-on


practice--to add a user defined exception, to check the total number of employees in a
department. Check if the total number of employees less than 10 then the procedure
raises an exception and print a message – “We need more good employees.”
A: >> DECLARE
-- define department statistics
CURSOR c_ds (p_deptno dept.deptno%type) IS
SELECT dname, count (*) ttemp,
sum(sal) ttsal, avg(sal) avsal
FROM dept d, emp e
WHERE d.deptno = e.deptno
GROUP BY dname;
-- define deptno variable
v_deptno NUMBER(2);
not_enough_emp EXCEPTION;
BEGIN
-- assign deptno 10
v_deptno := 10;
-- loop to read cursor record.
FOR v_ds in c_ds (v_deptno) LOOP
IF v_ds.ttemp < 10 THEN
raise not_enough_emp;
END IF;
-- insert into dept_stat
INSERT INTO dept_stat
VALUES (v_ds.dname, v_ds.ttemp,
v_ds.ttsal, v_ds.avsal);
END LOOP;
-- save the insert transaction.
COMMIT;
EXCEPTION
-- example of user define exception
WHEN not_enough_emp THEN
dbms_output.put_line(‘We need more employees’);
-- check deptno
WHEN invalid_number THEN
dbms_output.put_line(‘Invalid deptno: ‘ || v_deptno);
WHEN others THEN
dbsm_output.put_line(‘Other problem.’);
END;
/

Q: How do you write a PL/SQL language using NOTEPAD?


A: I just open NOTEPAD, write my PL/SQL program, and then save it.

Q: Create a table to keep your customer’s portfolio statistics and name it


CUST_STAT.
You should populate into this table a customer last name, his/her traded date, and total
stock market value for the traded date.
See the following columns and datatypes:
customer_lname VARCHAR2(20)
trade_date DATE
portfolio_value NUMBER(8,2)
A: SQL> CREATE TABLE cust_stat
(customer_lname VARCHAR2(20),
trade_date DATE,
portfolio_value NUMBER(8,2));

Q: Write a stored procedure to populate the customer statistics table. Declare a


cursor to query all the customer last names, the traded date, and the total stock
market value for the traded date. Use a sub-query with a MAX (trade_date)
function to guarantee the current stock market value for the traded date.
In the PL/SQL body, use the “FOR LOOP” statement to read the cursor
information one record at a time. Then insert the summary statistics data into the
customer statistics table. Use “commit” to save the transaction. In the exception
section, add the “no data found” exception and use the “dbms_output” package
to display the error message. Add the “invalid number” exception to detect any
invalid input data into the insert command. Add the “Others” exception to detect
other problems. Always use the “others” exception in case you miss some other
exceptions.
A: CREATE OR REPLACE PROCEDURE cust_stat_proc
IS
-- define cursor
CURSOR c_cs IS
SELECT last_name, trade_date,
sum(shares_owned*current_price) portfolio_value
FROM customers, portfolio, stocks s
WHERE id = customer_id AND stock_symbol = symbol
AND trade_date = (SELECT max(trade_date) FROM stocks
WHERE symbol = s.symbol)
GROUP BY last_name, trade_date;
BEGIN
FOR v_cs in c_cs LOOP
- insert into cust_stat
INSERT INTO cust_stat
VALUES (v_cs.last_name, v_cs.trade_date,
v_cs.portfolio_value);
-- save the insert transaction.
COMMIT;

END LOOP;

EXCEPTION
-- no data found
WHEN no_data_found THEN
dbms_output.put_line(‘No data found.’);
WHEN invalie_number THEN
dbsm_output.put_line(‘Invalid number’);
WHEN others THEN
dbsm_output.put_line(‘Other problem.’);
END;
/

Q: Then run your created procedure.


A: SQL> EXECUTE cust_stat;

Q: Verify that your table was populated.


A: SQL> SELECT * FROM cust_stat;

Q: What is the Procedure Builder Tool?


A: The procedure Builder tool is a software utility that helps developers to write, debug,
save,
and test their PL/SQL programs.

Q: What is the listener in the Oracle database?


A: A listener is an Oracle agent that monitors a specific port. It is a gateway of
communication
between clients and Oracle server.
Q: How do you start or stop your listener?
A: On NT, that will be done automatically.
On UNIX, just type: $ lsnrctl start – to start and
$ lsnrctl stop -- to stop

Q: What is the Object Navigator in the Procedure Builder tool?


A: The Object Navigator window is a place that a developer can browse and navigate
all its created objects.

Q: How to you open a database using the Procedure Builder tool?


A: Select the ‘connect’ option in the File menu.

Q: What is a user’s schema?


A: We have user’s schema if the user owns objects. No objects no schema.

Q: What type of objects can you have under a schema?


A: Tables, Indexes, Procedures, Packages, Functions, Synonyms, etc.

Q: How do you create a procedure using the Procedure Builder Tool?


A: In the ‘Object Navigator’ window, highlight "Program Units” and click on the
green ‘+’ sign which is the ‘Create’ icon.

Q: What is a Program Unit?


A: It is a stored procedure such as procedure, function, package body, and package
specification.

Q: Write a PL/SQL stored procedure to add a record into the department table (dept).
You use three input parameters to pass the department's columns (Department number
“DEPTNO,” department name “DNAME,” and department location “LOC”); and use
one output parameter to check the status of the insert transaction. You should use
the Procedure Builder.

Note that you should use the "p_" prefix to name the parameters. You use this parameter
as
an output parameter to check the status of your transaction. Use comments in your
programs. Use double dashes for a single line comment. And use “/*” ended with “*/”
for a multiple lines comment. In the “EXCEPITON” section, define the exception.
Use the “duplicate value on index” exception, the “invalid number” exception, and
the “OTHERS” exception. Use the others in case you are missing other exceptions.
A: PROCEDURE add_dept
(p_deptno IN dept.deptno%TYPE,
p_dname IN dept.dname%TYPE,
p_loc IN dept.loc%TYPE,
p_status OUT VARCHAR2)
IS
-- No variable
BEGIN
/* This program add dept. record. */
INSERT INTO dept
VALUES (p_deptno, p_dname, p_loc);
--- Save record.
COMMIT;
-- Added successfully if the get to this line.
p_status := ‘OK’;

EXCEPTION
-- Check for an Unique or Primary Key
WHEN dup_val_on_index THEN
p_status := ‘DUPLICATE RECORD’;
-- Check for invalid input data
WHEN invalid_number THEN
p_status := ‘INVALID INPUT DATA’;
-- Check for any other problems
WHEN others THEN
p_status := ‘CHECK THIS WE HAVE UNKNOWN PROBLEM.’;

END add_dept;
/

Q: Write a stored procedure to test the ‘add_department’ procedure. Declare a status


variable and make sure to call the “add_department” procedure. Enter an invalid
department
number to see the exception error message. To display the status of your transaction
value, use the TEXT_IO instead of the DBMS_OUTPUT, when you run the procedure
locally.
A: PROCEDURE test_add_dept
-- This procedure will test add_dept procedure
v_status VARCHAR2(40);
BEGIN
-- Call add_dept with an invalid number.
add_dept(100, ‘FINANCE’, ‘OHIO’, v_status);
-- Print ‘OK’ value if there is no error.
TEXT_IO.PUT_LINE(v_status);
EXCEPTION
WHEN others THEN
p_status := ‘CHECK THIS WE HAVE UNKNOWN PROBLEM.’;
END test_add_dept;
/

Q: What is the client side environment?


A: It is when we store the PL/SQL stored procedures in a PC or a Server that
Oracle server doesn’t reside in.
Q: What is the server side environment?
A: It is when we store the PL/SQL stored procedures in the Oracle database.

Q: How do you save the above PL/SQL procedure in your local library?
A: To save the program in the local library, go to the ‘Object Navigator’ window,
highlight PL/SQL libraries and click on the create icon. Click “OK.” Choose the
“File” option and select “Save as.” Save any name library in a folder. Then click
“OK” as “File System.” A library should be created. Now, drag the procedure
into its “Program Units.” Highlight the library name and save it again.

Q: Write a procedure to remove a department record. Make sure to define


one input parameter for the department number; and an output parameter as
a status parameter. You will use this parameter to test the status of the deleted
transaction.

In the PL/SQL body, delete the department record where its department
number matches with the input department number parameter. Save the
deleted transaction and assign "OK" to the status output parameter for a
successful deleted transaction.
A: PROCEDURE remove_dept
(p_deptno IN dept.deptno%TYPE,
p_status OUT VARCHAR2)
IS
-- Delete a record
DELETE FROM dept
WHERE deptno = p_deptno;
-- Save the transaction.
COMMIT;
-- Check the status.
p_status := ‘OK’;
EXCEPTION
WHEN no_data_found THEN
p_status := ‘NO DATA FOUND.’;
WHEN others THEN
p_status := ‘Other Problems.’;
END remove_dept;
/

Q: Write a PL/SQL procedure to test the above-created PL/SQL procedure.


A: PROCEDURE test_remove_dept
-- This procedure will test remove_dept procedure
v_status VARCHAR2(40);
BEGIN
-- Call remove_dept with a valid number.
remove_dept(40, v_status);
-- Print ‘OK’ value if there is no error.
TEXT_IO.PUT_LINE(v_status);
EXCEPTION
WHEN others THEN
p_status := ‘CHECK THIS WE HAVE UNKNOWN PROBLEM.’;
END test_remove_dept;
/

Q: What does the TEXT_IO package?


A: It displays the results on the screen.

Q: Name one procedure that is in the TEXT_IO package.


A: PUT_LINE

Q: What are the differences between the TEXT_IO and DBMS_OUTPUT packages?
A: You use the TEXT_IO package in a client environment but use the
DBMS_OUTPUT package in a server environment.

Q: What is the PL/SQL function?


A: It is a stored procedure that can have none or many input parameters,
but it returns one and only one value.

Q: What are the differences between the PL/SQL function and procedure?
A: A function returns one and only one value but procedure can have many outputs.

Q: When do you create the PL/SQL function?


A: CREATE OR REPLACE FUCNTION function_name IS

Q: write a PL/SQL Function to concatenate the customer's last name and first name to
be
separated by a comma. For example: Kazerooni, John. Name the function "Full_Name,”
and declare a datatype for the Function return value. Declare a first name and last name
input parameters. Their datatypes should match with the datatype of the firstname and
lastname in the customers table.
In the PL/SQL body, return the customers’ concatenated name. Write the exception.
In the exception section, do nothing in the case of an error handling exception.
A: FUNCTION full_name
(p_fname IN customers.first_name%TYPE,
p_lname IN customers.last_name%TYPE)
RETURN VARCHAR2
IS
-- No variables
BEGIN
-- Full name concatenation…
RETURN p_lname || ‘, ‘ || p_fname;
EXCEPTION
WHEN others THEN
-- Do nothing…
NULL;
END full_name;
/

Q: How do you execute the above created PL/SQL function in the SQLPLUS tool?
A: PL/SQL> SELECT full_name(‘John’,’Kazerooni’)
FROM dual;

Q: What is the PL/SQL interpreter?


A: The PL/SQL interpreter is a module that allows the developers to run and debug
their
stored procedures. It reads PL/SQL statements interactively.

Q: How do you execute a PL/SQL procedure in the PL/SQL interpreter?


A: Just type the procedure name ended with a semicolon.

Q: Write a PL/SQL Function to return the department name (dname). You use one
input
parameter to pass the department number (DEPTNO) and return its department name.
A: FUNCTION dept_name
(p_deptno IN dept.deptno%TYPE)
RETURN VARCHAR2
IS
-- Define dname variable
v_dname dept.dname%TYPE;
BEGIN
-- Get department name
SELECT dname INTO v_dname
FROM dept
WHERE deptno = p_deptno;
-- Return department name.
RETURN v_dname
EXCEPTION
-- Error messages…
WHEN no_data_found THEN
RETRUN ‘NO DATA FOUND…’;
WHEN others THEN
RETURN ‘Other PROBLEM…’;
END dept_name;
/

Q: In the “PL/SQL interpreter” section, use the “select” statement and use the
department number
10 to test the function.
A: PL/SQL> SELECT dept_name(10) as “Department Name”
FROM dual;
Q: To test the exception, call the function again using the department number that does
not exist
in the department table.
A: PL/SQL> SELECT dept_name(55) as “Department Name”
FROM dual;

Q: Query the department name function against the employee table sorted by the
employee name.
A: PL/SQL> SELECT ename, dept_name(deptno) as “Department Name”
FROM emp
ORDER BY 1;

Q: How do you debug a PL/SQL procedure?


A: We should use the Procedure Builder debugger module. Choose the "Program"
option and
open the PL/SQL interpreter. Then run the procedure that needs to be debugged.

Q: How do you move a PL/SQL procedure to the PL/SQL interpreter’s source area?
A: Click on the icon next to the procedure and that will move the procedure's source
program
to the PL/SQL interpreter’s source area.

Q: What is the BREAKPOINT indicator in the PL/SQL interpreter?


A: It is a time the debugged program will stop and we can check the values of the
program
elements on that specific interruption time.

Q: How do you create a BREAKPOINT in the PL/SQL interpreter?


A: Double click on line number that contains an execution statement in order to make a
“BREAKPOINT.”
Then a big red dot will appears.

Q: How do you activate the Step Into, Step Out, and Reset icon in the PL/SQL
interpreter?
A: After defining the "breakpoint", you can run the debugged procedure which will
activate the
Step Into, Step Out, and Reset icons.

Q: What does the Step Into icon in the PL/SQL interpreter?


A: The "Step Into" icon takes us to the next line.

Q: What does the Step Out icon in the PL/SQL interpreter?


A: The "Step Out" icon takes us to the next cycle of a breakpoint.

Q: What does the Reset icon in the PL/SQL interpreter?


A: The "Reset" icon terminates the debug mode.

Q: What does the STACK section contain?


A: It contains the content of all variables.

Q: How can you see the columns and variables values in the PL/SQL program using the
PL/SQL interpreter?
A: On the stack section, expand "procedure body."

Q: Can you have multiple versions of a PL/SQL procedure in the PL/SQL library?
A: Yes.

Q: How can you copy a PL/SQL procedure to your database server?


A: Click and drag the procedure into “Stored Program Units.”

Q: What would be happen if you move or copy a locally PL/SQL procedure with its
local
packages into the database server?
A: The procedure will not be compiled in the database server.

Q: What is an Object Privilege?


A: The object privileges will allow users to manipulate the object by adding, changing,
removing, or viewing data plus the ALTER, REFERENCES, and EXECUTE privileges
in
the database object.

Q: What are System Privileges?


A: System privileges control the altering, dropping, and creating of all database objects,
such as
rollback segments, synonyms, tables, and triggers.

Q: How do you create a user in the Oracle database?


A: SQL> CREATE USER newuser IDENTIFIED BY newpass
DEFAULT TABLESPACE users
TEMPORARY TABLESPACE temp;

Q: How do you assign a default and temporary tablespace to a user in the Oracle
database?
A: SQL> ALTER USER newuser
DEFAULT TABLESPACE users
TEMPORARY TABLESPACE temp;

Q: What are the System Privileges in the RESOURCE and CONNECT roles?
A: The CONNECT role contains the following system privileges:
ALTER SESSION, CREATE CLUSTER, CREATE DATABASE LINK,
CREATE SEQUENCE, CREATE SESSION, CREATE SYNONYM,
CREATE TABLE, and CREATE VIEW.
The RESOURCE role contains the following system privileges:
CREATE CLUSTER, CREATE INDEXTYPE, CREATE OPERATOR,
CREATE PROCEDURE, CREATE SEQUENCE, CREATE TABLE,
CREATE TRIGGER, and CREATE TYPE.

Q: How do you grant an object privilege to a user?


A: SQL> GRANT SELECT ON customer TO newuser;

Q: How do you grant a system privilege to a user?


A: SQL> GRANT CREATE ANY TABLE TO newuser;

Q: What is the Public Synonym in the Oracle database?


A: It is a synonym that all Oracle users can use it.

Q: How do you create a PUBLIC SYNONYM?


A: SQL> CREATE PUBLIC SYNONYM customer FOR iself.customer;

Q: Why do you need a PUBLIC SYNONYM?


A: Easy of use and unique naming convention.

Q: What is the EXECUTE privilege? Is it a system privilege or an object privilege?


A: The EXECUTE privilege will be given to a user in order to run other Oracle user’s
stored procedures. It is an object privilege.

Q: Can you grant the EXECUTE privilege to a table?


A: No.

Q: What is the Private Synonym in the Oracle database?


A: It is used only privately for the creator of the object.

Q: What are the differences between a private synonym and public synonym?
A: The private synonym can not be accessed by public.

Q: How do you revoke a system privilege from an Oracle user?


A: SQL> REVOKE CREATE ANY TABLE FROM newuser;

Q: How do you revoke an object privilege from an Oracle user?


A: SQL> REVOKE SELECT ON emp FROM newuser;

Q: Mr. A granted to Mr. B an object privilege with a ‘WITH GRANT OPTION’ and
then
Mr. B granted the same privilege to Mr. C. You decide to revoke the Mr. B’s object
privilege.
What would be happen to Mr. C’s granted object privilege?
A: It will be revoked too.

Q: Mr. A granted to Mr. B a system privilege with a ‘WITH ADMIN OPTION’ and
then
Mr. B granted the same privilege to Mr. C. You decide to revoke the Mr. B’s system
privilege.
What would be happen to Mr. C’s granted system privilege?
A: Nothing.

Q: How do you know that a privilege is the system privilege or object privilege?
A: If there are not SELECT, INSERT, UPDATE, DELETE, REFERENCES,
EXECUTE,
and ALTER then they are system priviledges.

Q: On the GRANT ALL statement, what “ALL” means if your grant is on a PL/SQL
procedure?
A: It means execute only.

Q: What is an object dependency in the Oracle database?


A: An object may be created based on the existence of another object or objects. The
purity
of the created object depends on the status of the other objects that have already been
created.
If any of those objects changed or deleted, the new object can not perform its task
completely.
Therefore, Oracle will change its status to an INVALID mode.

Q: What is a timestamp?
A: When you create or change something in an object, it’s created or modified date will
be recorded.
It is called a timestamp. Now any objects that were using this object are going to have an
invalid status
since the timestamp shows a date that is after creation of those objects.

Q: How do you query all the objects that was create by you (your schema)?
A: SQL> SELECT object_name, object_type, status
FROM user_objects;

Q: How do you change a datatype of a column in a table?


A: SQL> ALTER TABLE dept
MODIFY (loc VARCHAR2(14));

Q: How do you compile a PL/SQL function?


A: SQL> ALTER FUNCATION dept_name COMPILE;

Q: What is the PL/SQL package?


A: A PL/SQL package is collection of stored procedures such as procedures and
functions.

Q: What are the components of a PL/SQL package?


A: A package should have a PL/SQL package specification and a PL/SQL package
body.

Q: What is a package body in the PL/SQL language?


A: A ‘PL/SQL package body’ contains a complete PL/SQL stored procedures or
functions.

Q: What is a package specification in the PL/SQL language?


A: A ‘PL/SQL package specification’ contains all your PL/SQL functions header,
procedures header,
type, variables, etc.

Q: Where do you save the package body and its package specification?
A: You can store them either in the client or server environments.

Q: Can you store a PL/SQL package in a client environment?


A: Yes.

Q: How do you create a package specification and body?


A: Package specification:
CREATE OR REPLACE PACKAGE pkg_dept IS
For Package BODY:
CREATE OR REPLACE PACKAGE BODY pkg_dept IS

Q: What are the dependencies between a package body and its package specification?
A: The package body contains the source programs and package specification contains
the header programs.

Q: Write a PL/SQL package to have all your created PL/SQL functions and procedures.
A: PACKAGE pkg_dept
IS
-- No variables
-- This is the add_dept specification…
PROCEDURE add_dept
(p_dept_rec IN dept%ROWTYPE,
p_status OUT VARCHAR2);
-- This is the remove_dept specification…
PROCEDURE remove_dept
(p_deptno IN dept.depno%TYPE,
p_status OUT VARCHAR2);
-- Add more and more…
END pkg_dept;
/

PACKAGE BODY pkg_dept


IS
-- Add department procedure…
PROCEDURE add_dept
(p_deptno IN dept.deptno%TYPE,
p_dname IN dept.dname%TYPE,
p_loc IN dept.loc%TYPE,
p_status OUT VARCHAR2)
IS
-- No variable
BEGIN
/* This program add dept. record. */
INSERT INTO dept
VALUES (p_deptno, p_dname, p_loc);
--- Save record.
COMMIT;
-- Added successfully if the get to this line.
p_status := ‘OK’;
EXCEPTION
-- Check for an Unique or Primary Key
WHEN dup_val_on_index THEN
p_status := ‘DUPLICATE RECORD’;
-- Check for invalid input data
WHEN invalid_number THEN
p_status := ‘INVALID INPUT DATA’;
-- Check for any other problems
WHEN others THEN
p_status := ‘CHECK THIS WE HAVE UNKNOWN PROBLEM.’;
END add_dept;
-- Remove department procedure…
PROCEDURE remove_dept
(p_deptno IN dept.deptno%TYPE,
p_status OUT VARCHAR2)
IS
-- Delete a record
DELETE FROM dept
WHERE deptno = p_deptno;
-- Save the transaction.
COMMIT;
-- Check the status.
p_status := ‘OK’;
EXCEPTION
WHEN no_data_found THEN
p_status := ‘NO DATA FOUND.’;
WHEN others THEN
p_status := ‘Other Problems.’;
END remove_dept;
-- And more internal procedures.
END pkg_dept;
/

Q: What is a public PL/SQL procedure or function in a PL/SQL package?


A: All the procedures that were declared in the package specification.

Q: What is a private PL/SQL procedure or function in a PL/SQL package?


A: Those procedures that are in the BODY but were not declared in the package
specification.

Q: What are the differences between a public or private PL/SQL procedure?


A: The private PL/SQL procedure can not be accessed by any users or objects.

Q: How do you run a PL/SQL procedure or function in a PL/SQL package?


A: PL/SQL> DECLARE
v_status VARCHAR2(40);
BEGIN
pkg_dept.remove_dept(40, v_status);
TEXT_IO.PUT_LINE(v_status);
END;
/

Q: What is a database trigger?


A: A database trigger is a set of PL/SQL statements that execute each time an event
such as an
update, insert, or delete statement occurs on the database. They are similar to stored
PL/SQL
statements. They are stored in the database and attached to a table.

Q: How do you create a trigger?


A: Select “Triggers” and click on the "create" icon.

Q: If you drop a table that contains a trigger, does its trigger drop?
A: Yes.

Q: Create a trigger to audit department table (dept) to keep track of all the insert,
update,
and delete transactions and insert the audited transaction to a table.
A: BEGIN
-- audit if the user inserted a record…
IF INSERTING THEN
INSERT INTO audit_dept
VALUES (user || ‘ inserted deptno: ‘ || :new.deptno);
-- audit if the user updated a record…
ELSIF UPDATING THEN
INSERT INTO audit_dept
VALUES (user || ‘ updated deptno: ‘ || :old.deptno);
-- audit if the user deleted a record…
ELSIF DELETING THEN
INSERT INTO audit_dept
VALUES (user || ‘ deleted deptno: ‘ || :old.deptno);
-- end if
END ID;
END;

Q: How do you compile a trigger?


A: In the trigger window, click save to compile. Then close the window.
Or SQL> ALTER TRIGGER trigger_name COMPILE;

Q: How do you disable or enable a trigger?


A: One way is:
PL/SQL> ALTER TRIGGER iself.audit_dept_table DISABLE:
PL/SQL> ALTER TRIGGER iself.audit_dept_table ENABLE:

Q: How do you test your created trigger?


A: Execute a SQL statement that should fire the created trigger.

Q: How do you modify a trigger?


A: In the Object Navigator, on the database item, double click on the trigger icon to
open the
trigger, and then modify the trigger.

Q: How do you drop a trigger?


A: PL/SQL> DROP TRIGGER “audit_dept_table”;

Q: When you drop a trigger, does its table drop?


A: NO.

Q: How do you increase the size of SERVEROUTPUT buffer?


A: SQL> SET SERVEROUTPUT ON SIZE 400000

Q: Can you perform a DDL statement in the PL/SQL block?


A: Not directly. You should use the Oracle packages to perform such task.

Q: How can you compile an object in a PL/SQL block?


A: SQL> BEGIN
DBMS_DDL.ALTER_COMPILE
('PROCEDURE','ISELF','TEST02_4DDL_PKG');
END
/

Q: What does the DBMS_DDL package?


A: It will perform the DDL statements in the PL/SQL stored procedures.

Q: What does the ANALZE_OBJECT procedure in the DBMS_DDL package and how
can you verify that the object was ANALYZED?
A: It analyze a table the same as the Oracle ANALYZE statement. We can use the
following SQL statement to verify that the object was ANALYZED or not.

SQL> SELECT
TO_CHAR (LAST_ANALYZED,'mm-dd-yy hh24:mi:ss')
last_analyzed_time
FROM
USER_TABLES
WHERE TABLE_NAME = 'TEST01_4DDL_PKG';

Q: What does the ALTER_COMPILE procedure in the DBMS_DDL package and how
can you verify that the object was compiled?
A: It will compile a procedure. We can use the following SQL statement to verify that
the object was compiled.
SQL> SELECT
object_name,
to_char
(last_ddl_time,'mm-dd-yy hh24:mi:ss') ddl_time
FROM
user_objects
WHERE object_name = 'TEST02_4DDL_PKG';

Q: What is a Native Dynamic SQL statement?


A: Native Dynamic SQL allows an application to run SQL statements whose contents
are not known until runtime. The statement is built up as a string by the application and is
then passed to the server. Generally dynamic SQL is slower than static SQL so it should
not be used unless absolutely necessary. Make sure to check the syntax, since syntax
checking and object validation cannot be done until runtime. The only advantage of
dynamic SQL is that it allows you to perform DDL commands and also allows you to
access objects that will not exist until runtime.

Q: Write a stored procedure to pass the table name and get back the number of records
that table contains. The SELECT statement must be created dynamically, since you don’t
know what table you are getting statistics from. You should write your function so that
your client can display the tables’ name, plus the number of records contained each table.
A: SQL> CREATE OR REPLACE FUNCTION get_total_recs
(loc VARCHAR2)
RETURN NUMBER IS
Query_str VARCHAR2(1000);
Num_of_recs NUMBER;
BEGIN
Query_str := 'SELECT COUNT(*) FROM ' || loc;
EXECUTE IMMEDIATE query_str INTO num_of_recs;
RETURN num_of_recs;
END;
SQL> /

Q: How do you check that you have the JAVA tool installed in your server?
A: SQL> SELECT COUNT(*) FROM dba_objects
WHERE object_type LIKE 'JAVA%';

Q: What should it be at least size for the JAVA pool memory usage?
A: You must have at least 30 megabytes of memory.

Q: How do you create a JAVA class?


A: SQL> CREATE OR REPLACE JAVA SOURCE NAMED "iself" AS
public class iself {
static public String message (String tail) {
return "iSelfSchooling-" + tail;
}
}
SQL> /

Q: How do you publish a JAVA class?


A: SQL> CREATE OR REPLACE FUNCTION error_msg
(str VARCHAR2)
RETURN VARCHAR2
AS
BEGIN
LANGUAGE JAVA NAME
'iself.message (java.lang.String)
return java.lang.String';
END error_msg;
SQL> /

Q: How do you test a JAVA function?


A: SQL> SELECT error_msg ('01320: Running JAVA was successful.')
as "Message Function"
FROM dual
SQL> /

Q: How do you drop a JAVA source and Function?


A: SQL> DROP JAVA SOURCE "iself";

Q: What does the EMPTY_BLOB() function?


A: Empty the photo column in the EMP table. The EMPTY_BLOB function returns an
empty locator of type BLOB (binary large object). Use EMPTY_BLOB to initialize a
BLOB to "empty." Before you can work with a BLOB, either to reference it in SQL
DML statements such as INSERTs or to assign it a value in PL/SQL, it must contain a
locator. It cannot be NULL. The locator might point to an empty BLOB value, but it will
be a valid BLOB locator.

Q: How do you create a directory in the Oracle database?


A: SQL> CREATE OR REPLACE
DIRECTORY photo_folder AS 'c:\ephoto';

Q: Does everyone can create a directory in the Oracle database?


A: NO.

Q: Write a stored procedure to read the employee number and its photo file name and
then store the employee’s picture into the EMP table.

A: SQL> CREATE OR REPLACE PROCEDURE insert_photo


(p_empno NUMBER, p_photo VARCHAR2)
AS
f_photo BFILE;
b_photo BLOB;
BEGIN
-- Update the employee photo
UPDATE emp
SET photo = empty_blob()
WHERE empno = p_empno
RETURN photo into b_photo;
-- find where the photo's pointer is located.
f_photo := bfilename('PHOTO_FOLDER', p_photo);
-- open the photo as read-only option.
dbms_lob.fileopen(f_photo, dbms_lob.file_readonly);
-- load the photo into column photo.
dbms_lob.loadfromfile(b_photo,f_photo, dbms_lob.getlength(f_photo));
-- close the photo's pointer.
dbms_lob.fileclose(f_photo);
-- Save the loaded photo record.
COMMIT;
EXCEPTION
-- Check for your error messages
WHEN others THEN
dbms_output.put_line('*** ERROR *** Check you procedure.');
END;
SQL> /

Q: How do you test that there is a picture in a column?


A: SQL> SELECT empno, ename,
dbms_lob.getlength(photo) "Photo Size"
FROM emp
SQL> /

Q: What does the DBMS_LOB package?


A: The DBMS_LOB package contains procedures and functions that manipulate Oracle
large objects.

Q: What does the GETLENGTH() function in the DBMS_LOB package?


A: The GETLENGHT() procedure is one of the stored procedures in the DBMS_LOB
package. It returns the size of a large object in the Oracle database.

Q: How do you drop a directory from your Oracle database?


A: SQL> DROP DIRECTORY photo_folder;

Q: How and when do you grant the CREATE ANY DIRECTORY privilege to a user?
A: How:
SQL> GRANT CREATE ANY DIRECTORY TO iself
When a user needs to write or read from that folder.

Q: How do you revoke the CREATE ANY DIRECTORY privilege from a user?
A: SQL> REVOKE CREATE ANY DIRECTORY FROM iself

Q: What is PL/SQL?
A: PL/SQL is a language that was provided by Oracle. Stored procedure is a collection
of PL/SQL. Stored procedure is like a program module in Oracle. It is available for
developers to code stored procedures that easily integrate with database objects via the
SQL statements such as INSERT, UPDATE, DELETE, and SELECT. This language
offers variable DECLARATION, LOOP, IF-THEN-ELSE-END IF, EXCEPTION an
advanced error handling, cursor, and more.

Q: Where can you store a PL/SQL procedure?


A: A PL/SQL stored procedure can be stored in an Oracle Database server or user client
machine in a PL/SQL library.

Q: What is the PL/SQL body section?


A: It is a section in a stored procedure to execute PL/SQL statements. It is also called
the execution section.

Q: What is the PL/SQL declaration section?


A: It is a section that all program variables, cursors, and types will be declared.

Q: An implicit cursor must have _________ on its SELECT SQL statement?


A: INTO

Q: Write an anonymous stored procedure to use the implicit cursor to query the
department table information where deptno is 30. Check, if no record was found then
print “Record was not found.” Else print the department name only.
A: >>DECLARE
V_DREC DEPT%ROWTYPE;
BEGIN
SELECT DEPTNO, DNAME, LOC INTO
V_DREC.DEPTNO,V_DREC.DNAME, V_DREC.LOC
FROM DEPT
WHERE DEPTNO = 30;
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('RECORD WAS NOT FOUND.');
ELSE
DBSM_OUTPUT.PUT_LINE(V_DREC.DNAME);
END IF;
END;
/

Q: What are the differences between the explicit and implicit cursors?
A:
4- Explicit cursor will be defined in the declaration section but implicit cursor will
be defined in the execution or body section.
5- The implicit cursor must have INTO clause in its SQL statement.
6- The explicit cursor can return more than one record but the implicit cursor should
only return one and only one record.

Q: Declare a cursor to list the department name (dname), total number of employees
(ttemp), total salary (ttsal), and average salary (avsal) for each department from the
department table and employee table order by the department name. Write all department
name with their total number of employees for each department. List only the department
name that their total number of employees is more than 100.
For example: ACCOUNTING has 145 employees.
(Note: Don’t use the ttemp, ttsal, and avsal item at this time)
A: DECLARE
-- define department statistics
d, emp e
WHERE d.deptno = e.deptno
GROUP BY dname
ORDER CURSOR c_ds IS
SELECT dname, count (*) ttemp,
Sum (sal) ttsal, avg(sal) avsal
FROM dept BY 1;
BEGIN
-- FOR LOOP statement to read cursor record.
FOR v_ds IN c_ds LOOP
IF v_ds.ttemp > 100 THEN
DBMS_OUTPUT.PUT_LINE
(v_ds.dname ||
‘ has ’ || v_ds.ttemp || ‘ employees.’);
END IF;
END LOOP;
END;
/

Q: Write a PL/SQL Function to return the department name (dname). You use one
input parameter to pass the department number (DEPTNO) and return its department
name.
A: CREATE OR REPLACE FUNCTION dept_name
(p_deptno IN dept.deptno%TYPE)
RETURN VARCHAR2
IS
-- Define dname variable
v_dname dept.dname%TYPE;
BEGIN
-- Get department name
SELECT dname INTO v_dname
FROM dept
WHERE deptno = p_deptno;
-- Return department name.
RETURN v_dname
EXCEPTION
-- Error messages…
WHEN no_data_found THEN
RETRUN ‘NO DATA FOUND…’;
WHEN others THEN
RETURN ‘Other PROBLEM…’;
END dept_name;
/

Q: How do you revoke a system privilege from an Oracle user?


A: REVOLE CREATE ANY TABLE FROM scott;
Q: Mr. A granted to Mr. B an object privilege with a ‘WITH GRANT OPTION’ and
then Mr. B granted the same privilege to Mr. C. You decide to revoke the Mr. B’s object
privilege. What would be happen to Mr. C’s granted object privilege?
A: Mr. C will lose his granted object privilege too.

Q: How do you change a datatype of a column in a table?


A: ALTER table_name MODIFY (column_name new_datatype);

Q: What is a PL/SQL package?


A: A package is a collection of procedures and functions together as an object.

Q: What is a package specification?


A: A package should have a PL/SQL package specification and a PL/SQL package
body. A ‘PL/SQL package specification’ contains all your PL/SQL functions,
procedures, type, variables, etc. All the declared PL/SQL functions, procedures,
variables, etc in a package specification are called public procedures and functions. They
can be accessible to the users who have privilege to execute them. In the PL/SQL
package specification, all the functions and procedures must have a PL/SQL procedure in
its PL/SQL package body. It is not necessary that all the PL/SQL procedures in a PL/SQL
package body have a specification entry in its PL/SQL package specification. Those
PL/SQL procedures that have not have any specification entry in the PL/SQL package
specification called private PL/SQL procedures.

Q: What are the differences between the statement and row triggers in the Oracle
database?
A: There are two types of database triggers: statement triggers and row triggers. A
statement trigger will fire only once for a triggering statement. A row trigger fires once
for every row affected by a trigger statement. Triggers can be set to fire either before or
after Oracle processes the triggering insert, update, or delete statement.

Q: What do the UPDATING, DELETING, or INSERTING keywords?


A: The keywords updating, deleting, or inserting can be used when multiple triggering
events are defined. You can perform different action based on the UPDATE, DELETE,
or INSERT statement that you are executing.

Q: How do you enable, disable, and drop a trigger in the Oracle database?
A: ALTER TRIGGER iself.audit_dept_table DISABLE:
ALTER TRIGGER iself.audit_dept_table ENABLE:
DROP TRIGGER iself.audit_dept_table;

Q: What does the following PL/SQL statements? What is the output of the following
SQL statement?
SQL> SELECT full_name (‘Joe’, ‘Smith’) as “Full Name” FROM DUAL;
CREATE OR REPLACE FUNCTION full_name
(p_fname IN customers.first_name%TYPE,
p_lname IN customers.last_name%TYPE)
RETURN VARCHAR2
IS
-- No variables
BEGIN
-- Full name concatenation…
RETURN p_lname || ‘, ‘ || p_fname;
EXCEPTION
WHEN others THEN
-- Do nothing…
NULL;
END full_name;
/

The output is:


Full Name
-----------------
Smith, Joe

Oracle Performance Tuning


Fundamental Exam Answers
NOTE: The answers go with their sequences. If a question was not answer, that means
that it a repeating question and the answer was given by the previous questions or it is not
in the scope of this subject.

“What we see depends mainly on what we look for.”

--Sir John Lubbock


Answers:
Q: What are the Oracle Architectural components?
A: The Oracle Architectural components are:
• Memory (SGA) such as Buffer Cache, Shared Pool, Redo Log Buffer, Large Pool,
Java Pool, etc.
• Background Processes such as Log Writer, DB Writer, Checkpoint, Archiver,
SMON, etc.
• Oracle Physical Layout such as Datafiles, Controlfiles, Online Redo log files,
Parameter file, Password file, etc.

Q: What are the Oracle Memory Components?


A: All components such as Shared Pool (Library Cache, Dictionary Cache), Buffer
Cache, Online Redo Log file, Large Pool, Java Pool as well as a few other items are
referred to as the System Global Area (SGA). And the place stores information like bind
variable values, sort areas, cursor handling, etc for a specific user is called Program
Global Area (PGA). The PGA is used to store only real values in place of bind variables
for executing SQL statements. The combination of these two memories structure while
they are running is called Oracle Instance.

Q: What is the Server Parameter File?


A: The Server Parameter File is a binary file and Oracle uses it to change the most of its
system parameters dynamically.

Q: What is the Parameter File?


A: The Parameter file is a configuration file and it contains all the Oracle instance and
database configuration parameters. When you change any parameter using this file, you
should shutdown and startup the Oracle Database.

Q: How do you use the init.ora file?


A: The init.ora file is called initialized or parameter file. It is a configuration file.

Q: What is the System Global Area (SGA)?


A: The SGA contains of Shared Pool (Library Cache, Dictionary Cache), Buffer Cache,
Online Redo Log file, Large Pool, Java Pool as well as a few other items.

Q: What is the Shared Pool in SGA?


A: The Shared Pool contains the Library Cache and the Dictionary Cache as well as a
few other items, which are not in the scope of this section. The Library Cache holds all
users’ SQL statements, Functions, Procedures, and Packages. It stores parsed SQL
statement with its execution plan for reuse. The Dictionary Cache, sometimes also
referred to as the Row Cache, holds the Oracle repository data information such as tables,
indexes, and columns definitions, usernames, passwords, synonyms, views, procedures,
functions, packages, and privileges information.

Q: What does the Buffer Cache hold in SGA?


A: The Buffer Cache holds users’ data. Users query their data while they are in the
Buffer Cache. If user’s request is not in the Buffer Cache then server process has to bring
it from disk. The smallest unit in the buffer cache is an Oracle block. The buffer cache
can be increased or decreased by granule unit. The smallest Granule Unit is 4Meg if the
SGA size is less than 128Meg and the smallest Granule Unit become 16Meg is the SGA
size is more than 128Meg.

Q: What are the differences between the Library Cache and Dictionary Cache?
A: The Library Cache holds user’s SQL statements, PL/SQL programs, but the
Dictionary Cache holds only repository information such as user’s table name, its access
privileges, and etc.

Q: What is the Redo Log Buffer in SGA?


A: The Redo Log Buffer holds users’ entries such as INSERT, UPDATE, DELETE, etc
(DML) and CREATE TABLE, DROP TABLE (DDL). The Redo Entries are information
that will be used to reconstruct, or redo, changes made to a database. The Log
Writer writes the entries into the Online Redo Log files when a COMMIT occurs, every 3
seconds, or when one third of the Redo Log Buffer is full. That will guarantee a database
recovery to a point of failure if an Oracle database failure occurred.

Q: Describe the Large Pool component in SGA.


A: The Large Pool holds information about the Recovery Manager (RMAN) utility
when RMAN is running. If you use the Multi-threaded Server (MTS) process, you may
allocate the Oracle Memory structure such that you can get advantage of using Large
Pool instead of the Shared Pool. Notice that when you use dedicated servers, user session
information is housed in the PGA.

Q: Describe the Multi-threaded Server process.


A: The Multi-threaded Server process will be used when a user send his/her request by
using a shared server. A user’s request will be assigned to a dispatcher based on the
availability of dispatchers. Then the dispatcher will send or receive request from an
assigned shared server.

Q: What are PGA and UGA?


A: When you are running dedicated servers then the session information can be stored
inside the process global area (PGA). The UGA is the user global area, which holds
session-based information. When you are running shared servers then the session
information can be stored inside the user global area (UGA).

Q: Describe the log writer background process (LGWR).


A: The LGWR’s job is to write the redo user’s entries from the Redo Log Buffer.

Q: How often does LGWR write user’s entries to the Online Redo Log Buffer files?
A: It writes user’s entries when the buffer exceeds one third of the Redo Log Buffer,
every 3 seconds, or when a user executes the commit SQL statement.

Q: Describe the Checkpoint process.


A: The Checkpoint signals DB writers to write all dirty blocks into the disk. The
Checkpoint will occurred either by a specific defined time, size of the Online Redo Log
file used by DBA, or when an Online Redo log file will be switched from on log file to
another.

Q: How do you automatically force the Oracle to perform a checkpoint?


A: The following are the parameters that will be used by a DBA to adjust time or
interval of how frequently its checkpoint should occur on its database.
LOG_CHECKPOINT_TIMEOUT = 3600 # every one hour
LOG_CHECKPOINT_INTERVAL=1000 # number of OS blocks

Q: What is the Recovery Process?


A: The RECO will be used only if you have a distributed database. You use this process
to recover a database if a failure occurs due to physical server problem or communication
problem.

Q: What is the Lock Background Process?


A: The LCKn background process will be used if you have multiple instances accessing
to only one database. An example of that is a Parallel Server or a Real Application
Clusters.

Q: How does the Archive Process work?


A: This background process archives the Online Redo Log file when you are manually
or automatically switching an Online Redo Log file. An example of manually switching
is: ALTER SYSTEM SWITCH LOGFILE or ALTER SYSTEM ARCHIVE LOG
CURRENT.

Q: How do you configure your database to do an automatic archiving?


A: SQL> ALTER SYSTEM ARCHIVE LOG CURRENT;

Q: What is the System Monitor Process?


A: The SMON job is: when you start your database, it will make sure that all datafiles,
controlfiles, and log files are synchronized before opening a database. If they are no, it
will perform an instance recovery. It will check the last SCN that was performed against
the datafiles. If it finds that there are transactions that were not applied against the
datafile, then it will recover or synchronize the datafile from either the Online Redo Log
files or the Archive Log files. The smaller Online Redo log files will bring a faster
database recovery.

Q: Describe the Program Monitor Process Job.


A: A user may be disconnected either by canceling its session or by communication
link. In either act, the PMON will start and perform an action to clean the reminding
memory allocation that was assigned to the user.

Q: What are the differences between the SPFILE and PFILE startup?
A: You can read or change the init.ora file (PFILE) for startup of the Oracle database. It
contains all Oracle parameters file to configure a database instance. In this file, you can
reset and change the Buffer Cache size, Shared Pool size, Redo Log Buffer size, etc. You
also can change the location of your control files, mode of a database such as archivelog
mode or noarchivelog mode, and many other parameter options that you will learn them
in the course of this book.
But using Server Parameter File-SPFILE, you can not read the file. It is in a binary
format. If you want to change database parameters dynamically, you should create the
Server Parameter file (CREATE SPFILE FROM PFILE) and startup your database using
the SPFILE file. There are some few parameters that you still need to shutdown and
startup the database, if you want to make the parameter in effect.

Q: What is the controlfile?


A: You cannot read this file and it is in a binary format. If you want to see the content of
control file or the layout of your database, you should use the ALTER DATABASE
BACKUP CONTROLFILE TO TRACE statement. It writes a trace file into the
%ORACLE_BASE\admin\<db-name>\UDUMP directory.

Q: How do you backup your database controlfiles?


A: SQL> ALTER DATABASE BACKUP CONTROLFILE TO c:\ctnlrfl.bk;

Q: What does a controlfile contain?


A: It contains information the structure of your database layout, database name, last
System Change Number (SCN) number, your database mode (archivelog mode or
noarchivelog mode), maximum number of log files, maximum number of log members,
maximum number of instances, maximum of number of datafiles, the location of the
database Online Redo Log files, and backup information.

Q: Describe the password file.


A: The password file is an external file that contains the password of sysdba or sysoper.
To use the password file you should set the REMOTE_LOGIN_PASSWORD parameter
to exclusive or shared mode in the Parameter File (Example:
REMOTE_LOGIN_PASSWORD=EXCLUSIVE).

Q: How do you create a password file?


A: To create the password file, you should run the ORAPWD utility from operating
system.
For example:
MS-DOS> ORAPWD FILE=%ORACLE_HOME\dbs\orapw<sid>.pwd \
PASSWORD=mypass ENTRIES=3
The ENTRIES parameter specifying the number of user entries allowed for the password
file. Now, the DBA can be connected to the database as a user with sysdba privilege.

Q: Describe the Online Redo Log file.


A: The Online Redo Log files hold the Redo Entries. You should have at least two or
more Redo Log Groups. Each group may have more than one member. It is a good
practice to multiplex Online Redo Log members. The Redo Entries are information that
will be used to reconstruct, or redo, changes made to a database. The Log Writer writes
the entries into the Online Redo Log files when a COMMIT occurs, every 3 seconds, or
when one third of the Redo Log Buffer is full. That will guarantee a database recovery to
a point of failure if an Oracle database failure occurred.
Q: How do you perform tuning on your database?
A: When there are complain about application performance, we should look at the
problem with the following sequence.

1- SQL Statement tuning,


2- Optimizing sorting Operations,
3- Memory Allocation.
a- Operating System Memory size,
b- Oracle allocated Memory size (SGA-System Global Area),
4- I/O contentions,
5- Latches & Locks,
6- Network Load.

Q: What is a Granule Unit?


A: The Granule Unit is the smallest unit that the SGA components are allocated and de-
allocated in units of contiguous memory. So it is very important that the amount of
allocated memory must be a product of the Granule size and an integer. If it is not then
the Oracle database will round them.

Q: How does a granule unit work in an increasing or decreasing the database memory?
A: You only can increase or decrease the SGA based on the Granule Unit. Therefore,
the size you allocate or de-allocate must be a multiple of a Granule Unit size. For
example: if your granule unit size is 4Meg bytes and you increate the size of your buffer
cache with 9Mg bytes more memory space then your Buffer cache will be allocated either
only 8Meg bytes of memory.

Q: If the size of your SGA is greater than 128M, what is the size of your database
granule unit?
A: If the SGA is larger than 128MB, then a granule is 16MB.

Q: If the size of your SGA is less than 128M, what is the size of your database granule
unit?
A: If the SGA is less than 128MB, then a granule is 4MB.

Q: What is the minimum number of granules allocated to the buffer cache, and the
shared pool?
A: The minimum number of granules allocated at startup is: 1 for the buffer cache, 1 for
the shared pool, and 1 for the fixed SGA, which includes redo buffers.

Q: How do you change a size of the shared pool?


A: ALTER SYSTEM SET shared_pool_size=100M scope=SPFILE;

Q: How do you keep an object in the Shared Pool memory?


A: Use the KEEP procedure to pin the STANDARD package.
SQL> BEGIN
SYS.DBMS_SHARED_POOL.KEEP('SYS.STANDARD');
END;
Q: How do you remove an object from the Shared Pool memory?
A: Use the UNKEEP procedure to pin the STANDARD package.
SQL> BEGIN
SYS.DBMS_SHARED_POOL.UNKEEP('SYS.STANDARD');
END;

Q: How do you calculate the Dictionary Cache Hit ratio value?


A: We should use the following SQL statement to calculate the overall dictionary cache
hit ratio.
SQL> SELECT (SUM(gets - getmisses)) / SUM(gets)
AS "Dictionary Hit Ratio"
FROM v$rowcache
/

Q: What are the Major components of the Shared Pool Memory?


A: The major components of the shared pool are: the library cache, the dictionary cache
(row cache), and the User Global Area (UGA).

Q: What is the User Global Area (UGA)?


A: The UGA is the user global area, which holds session-based information. When you
are running shared servers then the session information can be stored inside the user
global area (UGA) and when your session does some sorting, some of the memory
allocated for sorting - specifically the amount defined by parameter
sort_area_retained_size - comes from the SGA and the rest (up to sort_area_size) comes
from the PGA (Snnn).

Q: When does the Oracle database use UGA?


A: When you are running shared servers then the session information can be stored
inside the user global area (UGA).

Q: What does the SHARED_POOL_RESERVED_SIZE parameter?


A: That the SHARED_POOL_RESERVED_SIZE parameter can be reserved for large
objects.

Q: What does the DBMS_SHARED_POOL package?


A: The DBMS_SHARD_POOL package contains the stored procedures (functions
and/or procedures) that provide ease of use for the developers to manipulate size of the
shared pool, allocate objects in the shared pool, etc.

Q: How do you change the size of buffer cache in the SGA memory?
A: To increase or decrease the Buffer Cache size to a specific size.
SQL> ALTER SYSTEM SET db_cache_size=55M
/
Q: What is the Dynamic Buffer Cache Advisory parameter?
A: To assist you in the proper configuration, Oracle provided you with
the DB_CACHE_ADVICE parameter. When this parameter sets to ON, Oracle
begins collecting statistics about cache utilization and projects the physical I/O for 20
cache sizes, ranging from 10 to 200 percent of the current size.

Q: What is the Least Recently Used (LRU) list in the buffer cache memory?
A: The Least Recently Used (LRU) list is a list of blocks that have been used at the least
amount of time recently at the SGA memory.

Q: What is a Dirty Buffer in the Buffer cache memory?


A: The dirty buffers are blocks in the buffer cache that have been changed. The dirty
buffers are moved to the dirty list and written to data files by DB Writer
processes (DBWn).

Q: How do you perform tuning on the Buffer Cache Memory?


A: SQL> ALTER SYSTEM SET db_cache_advice=ON;
Notice that there are three possible values:
1 -- ON - allocates memory and gathers statistics.
2 -- OFF - disables advice statistic gathering.
3 -- READY - allocates memory, but statistics are not gathered.

Q: How do you check a SGA memory size?


A: SQL> SHOW PARAMETER sga

Q: How do you use the V$PARAMETER view?


A: You can use the V$PARAMETER view to query all the information that relate to the
SGA components.

SQL> SELECT SUM(value) as "SGA Size"


FROM v$parameter
WHERE name in
('shared_pool_size','db_cache_size','log_buffer','java_pool_size')
/

Q: How many lists are the buffers organized in the buffer cache?
A: The buffers in the buffer cache are organized in two lists:
1 -- The Least Recently Used (LRU) list, and
2 -- the Dirty list.

Q: How do you measure the buffer cache hit ratio?


A: To calculate the Buffer Cache Hit Ratio from the V$SYSSTAT view.
SQL> SELECT 1- ((p.value - l.value - d.value) / s.value)
AS "Buffer Cache Hit Ratio"
FROM v$sysstat s, v$sysstat l, v$sysstat d, v$sysstat p
WHERE s.name = 'session logical reads'
AND d.name = 'physical reads direct'
AND l.name = 'physical reads direct (lob)'
AND p.name = 'physical reads'
/

Q: How do you create a cache table?


A: To create a table to be kept in the KEEP buffer pool.
SQL> CREATE TABLE iself.mykeep
(col1 NUMBER,
col2 VARCHAR2(10))
STORAGE (BUFFER_POOL KEEP)
/

Q: How do you calculate a hit ratio for multiple pools?


A: To calculate the Hit Ratio for multiple pool:
SQL> SELECT name,
1-(physical_reads/(db_block_gets + consistent_gets)) "Hit Ratio"
FROM v$buffer_pool_statistics
WHERE db_block_gets + consistent_gets > 0
/

Q: How do you cache an object into the buffer pools using hint in a SQL statement?
A: To cache a table by hint in a SQL statement.
SQL> SELECT /*+ CACHE (iself.dept) */
*
FROM iself.dept
/

Q: What is a FREELIST?
A: The FREELIST space is an allocated space in a table that contains all the blocks’
references which are candidate for more inserted records. Any contentions on the
FREELIST allocation will create a performance problem.

Q: How do you diagnose the FREELIST contentions in the buffer cache?


A: To diagnose the FREELIST contention in the Buffer Cache.
SQL> SELECT s.segment_name, s.segment_type,
s.FREELISTs, w.wait_time,
w.seconds_in_wait, w.state
FROM dba_segments s, v$session_wait w
WHERE w.event='buffer busy waits'
AND w.p1=s.header_file
AND w.p2=s.header_block
/

Q: How do you use the DEFAULT pool?


A: The DEFAULT pool is used the same way as the standard Buffer Cache block size.

Q: How do you use the KEEP pool?


A: The KEEP buffer pool is used to keep buffers in the pool as long as possible for data
blocks that are likely to be reused.

Q: When do you use the RECYCLE pool?


A: The RECYCLE buffer pool is used as a temporary host block from segments that
you don't want to interfere with blocks in the DEFAULT Buffer Pool.

Q: What is the V$SYSSTAT view?


A: It is a view that contains the Oracle system usages such as session logical reads,
physical reads direct, etc.

Q: What is the V$BUFFER_POOL view?


A: It is a view that contains the Oracle buffer pool configurations. You can use this view
to query the buffer pool configurations information such as DEFAULT, KEEP, or
RECYCLE pools.

Q: What is the V$BUFFER_POOL_STATISTICS dictionary view?


A: It is a view that contains the Oracle buffer pools statistic. You can calculate the Hit
Ratio for multiple pools using this view.

Q: Describe the session logical reads, physical reads direct, and physical reads direct
(lob), and physical reads in the V$SYSSTAT view.
A: The ‘physical reads’ value is a number of read that Oracle physically performs from
hard disk including all the ‘physical reads direct’ and ‘physical read direct (lob).’ You
want to be sure that the ‘physical reads direct’ values be as high as possible in a respect to
the ‘physical reads’ value. Also, you want to be sure that the ‘session logical reads’ value
is very high. The ‘session logical reads’ value is the number of times that Oracle reads a
block from the memory (Buffer Cache) rather than a disk.

Q: What is an acceptable range for a buffer cache hit ratio?


A: If the Buffer Cache Hit Ratio is more than 90% then there is no problem. If the
Buffer Cache Hit Ratio is between 70% and 90% then there could be a problem. And if
the Buffer Cache Hit Ratio is less than 70%, there is definitely a problem and the Buffer
Cache size needs to be increased.

Q: What does the following SQL statement?


SQL> SELECT s.segment_name, s.segment_type,
s.FREELISTs, w.wait_time,
w.seconds_in_wait, w.state
FROM dba_segments s, v$session_wait w
WHERE w.event='buffer busy waits'
AND w.p1=s.header_file
AND w.p2=s.header_block
/
A: It will diagnose the FREELIST contention in the Buffer Cache. The
DBA_SEGMENTS view contains all the created users’ segments such as tables, indexes,
etc. The V$SESSION_WAIT view contains dynamic information for that instance and
for that specific time. Its content will be regenerated when you restart an instance. It
contains the contentions information such as ‘buffer busy waits’ for a file or a block, etc.

Q: How do you monitor the redo log buffer memory size?


A: Keep your eyes on the redo buffer allocation entries.
SQL> SELECT name, value
FROM v$sysstat
WHERE name = 'redo buffer allocation entries'
/
Note that if you have a positive number, that means that you may have a problem. Be
sure that you have compared the above positive number with the Redo entries and it
should not be more than 1%.
Also, you should query the redo allocation buffer entries ratio. Be sure that your ratio is
not more than 1%.
SQL> SELECT a.value/b.value "redo buffer entries ratio"
FROM v$sysstat a, v$sysstat b
WHERE a.name = 'redo buffer allocation entries'
AND b.name = 'redo entries'
/
If the number is greater than 1%, you should increase the size of the Redo Log buffer.

Q: How do you re-size the redo log buffer memory size?


A: ALTER SYSTEM SET log_buffer = 55M scope=SPFILE;

Q: How do you monitor a waiting session in the redo log buffer?


A: To check to see if there are any other sessions waiting for log buffer space to the
following SQL statement.
SQL> SELECT sid, event, seconds_in_wait, state
FROM v$session_wait
WHERE event = 'log buffer space'
/
If the Log Buffer space waits exist, consider increasing the size of the redo log. Also you
should check the speed of the disk that the Online Redo Log files are in.

Q: How do you monitor your online full redo log file?


A: To check to see if that Online Redo Log file is full and the server is waiting for the
next Redo Log file do the following SQL statement.
SQL> SELECT name, value
FROM v$sysstat
WHERE name = 'redo log space requests'
/

Q: Describe the redo log entries.


A: The redo entries in the redo log files are used for database recovery. The buffer is
usually flushed by reaching: one third of the redo log buffer size, frequent COMMITs,
and every 3 seconds.

Q: How do you reduce a database I/O problem?


A: In order to reduce the I/O contention we should at least consider the following steps:

01 -- Use Oracle to distribute the data files across multiple disks evenly.
02 -- Use the Oracle partitioning.
03 -- Use the locally managed tablespace option, unless you have a reason not to
do so.
04 -- Use only the Redo Log files, controlfiles, and dump files on the same disk.
05 -- Use all UNDO or ROLLBACK Segments on the same disk.
06 -- Use the Rollback and redo log files on a separate disk.
07 -- Use the data, index, SYSTEM, and UNDO tablespaces on a separate disk.
08 -- Use the data and temporary tablespaces on a separate disk.
09 -- Use the Redundant Array of Inexpensive Disks.
10 -- Use the raw device if possible.

Q: How do you monitor a database I/O problem?


A: To monitor the I/O transaction activity in the data files across multiple disks we
should write the following SQL statement.
SQL> SELECT file_name, phyrds, phywrts
FROM v$filestat a, dba_data_files b
WHERE a.file# = b.file_id
/

Q: How do you monitor the checkpoint process activities of a database?


A: To monitor the checkpoint process activities we should perform the following SQL
statement.
SQL> SELECT name, value
FROM v$sysstat
WHERE name like 'background check%'
/
If the "background check started" value is greater than the "background check
completed" value, you should increase the size of the REDO LOG files.

Q: How do you tune the checkpoint process activities?


A: You should just increase the size of the REDO LOG files.

Q: How do you use the V$SYSSTAT view?


A: You may use the V$SYSSTAT view to see how many times you have to scan the
short and long tables. If you the number of ‘table scans (long tables)’ was high then you
have done more IOs.
SQL> SELECT name, value
FROM v$sysstat
WHERE name IN ('table scans (short tables)',
'table scans (long tables)')
/
Try to reduce the number by creating proper table indexes. Note that the count for 'Long
Tables scan' must be very small.

Q: How do you use the V$SYSTEM_EVENT view?


A: We use the V$SYSTEM_EVENT directory view to monitor and tune a Redo Log
file parallel write.
SQL> SELECT event, total_waits, time_waited
FROM v$system_event
WHERE event = 'log file parallel write'
/
The "Waits" column indicates a possible I/O problem.

Q: How do you set the UNDO_MANAGEMENT parameter?


A: SQL> ALTER SYSTEM SET undo_management=AUTO SCOPE=spfile
/

Q: What does the UNDO_MANAGEMENT parameter?


A: When the system is in AUTO mode, and the transaction needs more space, Oracle
automatically will borrow more space from other undo segments that have extra space.

Q: Why and how do you distribute your tablespaces on different disks?


A: You should distribute the data files across multiple disks evenly.

Q: Describe RAID?
A: The RAID (Redundant Array of Inexpensive Disks) is some type of redundancy that
you can build in your system a part from Oracle in order to provided data duplication.
You can use RAID supported by hardware or software application. It is used in the case
of a disk crash or failure. Multiple disks can be formatted in a RAID format such that if
one of them fail, when you replace the bad disk with a new disk then all its data will be
regenerated from other disks.

Q: What does the SCOPE=spfile mean in the ALTER SYSTEM SET statement?
A: It means apply changes on the Server Parameter File only not on the memory. You
should restart the database using SPFILE in order to activate the changes.

Q: How do you optimize a sort operation in the Oracle SGA memory?


A: Query the V$SYSSTAT view to track the number of in-memory and to-disk sorts, as
well as the total number of rows sorted.
SQL> SELECT name, value
FROM v$sysstat
WHERE name like 'sorts%'
/
the sorts (disk) number must be very low, and the sorts (memory) number can be as high
as possible.

Q: Describe the ‘sorts (disk)’ value in the V$SYSSTAT view.


A: The ‘sorts (disk)’ value is a number of times that Oracle tables were sorted on the
disk using the TEMPORARY tablespace.

Q: How do you calculate the sort ratio value in the SGA sort area?
A: To calculate the sort ratio of the in-memory vs. to-disk sorts.
SQL> SELECT 100*(a.value-b.value)/(a.value) AS "Sort Ratio"
FROM v$sysstat a, v$sysstat b
WHERE a.name = 'sorts (memory)'
AND b.name ='sorts (disk)'
/

Q: What is an acceptable range for the sort ratio in the SGA sort area?
A: The sort ratio should be greater than 95%. If you are not using the automatic PGA
memory and the number is less than 95 percent, you should greatly consider increasing
the value of the SORT_AREA_SIZE parameter. If you are using the automatic PGA
memory and the number is less than 95 percent, you should greatly consider increasing
the value of the PGA_AGGREGATE_TARGET parameter.

Q: Describe a latch in the SGA memory.


A: A latch is a permission that Oracle gives to one server process at a time.

Q: What does a latch protect?


A: A Latch may protect shared memory allocation, or may also protect shared data
structures in the SGA.
Q: How do you diagnose contention for latches?
A: Check latch contention in the shared pool and redo log buffer.
1- To check latch contentions in the shared pool, we should do the following SQL
Statement:
SQL> SELECT name, (1-(misses/gets))*100
AS "Ratio", sleeps
FROM v$latch
WHERE name in ('library cache', 'shared pool')
/
The ratio must be above 99 percent.
2- To check the the Redo Allocation Latch and the Redo Copy Latch wait ratios.
SQL> SELECT h.pid, n.name, (l.misses/l.gets)*100 wait_ratio
FROM v$latchholder h, v$latchname n, v$latch l
WHERE h.laddr = l.addr
AND l.latch# = n.latch#
AND n.name in ('redo allocation', 'redo copy')
/
Notice that if there was an output and the wait ratio was more than 1, there is a problem.
Then, you will need to increase the Redo Log Buffer size.

Q: How many types of latch request does Oracle have?


A: Oracle has two different types of latch requests: willing to wait or immediate.

Q: What does a process do when a latch is willing to wait for a request and does not get
a latch?
A: The process waits briefly and then goes to sleep. Then, it requests the latch again.

Q: What does a process do when a latch is not willing to wait for a request and does not
get a latch?
A: In the immediate request, if the process cannot obtain the latch requested in the
immediate mode, it does not wait and does other jobs when it is finished, then it attempts
to obtain the latches again.

Q: How do you tune the UNDO segments?


A: Always set the UNDO_MANAGEMENT parameter to AUTO. In the AUTO option,
the database takes control of how to manage the UNDO segments.

Q: Describe the UNDO_RETENTION parameter.


A: The UNDO_RETENTION parameter indicates the number of seconds that the
database keeps the UNDO segments.

Q: Describe the UNDO_TABLESPACE parameter.


A: The UNDO_TABLESPACE parameter indicates the UNDO tablespace.
Q: Describe the V$UNDOSTAT view.
A: It is a view that contains all the undo segments statistics. You use it to calculate an
estimate of undo spaces to meet the undo retention requirement for an specific time such
as 15 minutes.
SQL> SELECT (xx*(ups*overhead) + overhead) AS "Bytes"
FROM (SELECT value AS xx
FROM v$parameter WHERE name = 'undo_retention'),
(SELECT (SUM(undoblks)/SUM((end_time-begin_time)*86400))
AS ups
FROM v$undostat),
(SELECT value AS overhead
FROM v$parameter
WHERE name = 'db_block_size')
/
The result of this query shows how much UNDO space we need to meet the UNDO
retention requirement.

Q: How do you get a list of UNDO segments?


A: SQL> SELECT * FROM v$rollname
/

Q: When do you get the following undo segment error message?


ORA-01555: snapshot too old.
A: When the UNDO segment is not big enough.

Q: What does the following SQL statement?


SQL> SELECT name, value
FROM v$sysstat
WHERE name in ('db block gets','consistent gets');
A: It queries the 'db block gets' and 'consistent gets' values. We use these two values to
calculate cache buffer hit ratio:
Hit Ratio = (db block gets + consistent gets - undo header) /
(db block gets + consistent gets)

Q: What is a lock contention in the Oracle database?


A: The Oracle server automatically manages object locking, so most application
developers don't need to focus on lock management. You should avoid any lock
contention. It does affect your performance very significantly. The lock contention is a
delay that Oracle is not able to lock a record or records due to exclusive use of that object
or objects.

Q: How do you monitor and detect a lock contention?


A: SQL> SELECT o.owner, o.object_name, o.object_type, l.type
FROM dba_objects o, v$lock l
WHERE o.object_id = l.id1
AND o.owner = 'ISELF'
/

Q: How do you lock a table in the exclusive mode?


A: SQL> LOCK TABLE iself.emp IN EXCLUSIVE MODE
/

Q: How do you lock a table in the shared mode?


A: SQL> LOCK TABLE iself.emp IN SHARE MODE
/

Q: How do you kill a session?


A: SQL> ALTER SYSTEM KILL SESSION '<sid,serial#>'
/

Q: Describe the different types of user locks.


A: The lock type can be TX, TM, and UL. If TYPE equals TX, it means
TRANSACTION ENQUEUE. If TYPE equals TM, it means DML ENQUEUE. If TYPE
equals UL, it means USER SUPPLIED.

Q: How do you optimize a SQL statement?


A: In order to optimize a SQL statement, you execute the EXPLAIN PLAN statement to
populate a list plan of execution in PLAN_TABLE. Then you write a SQL statement
against the table to query a plan of execution list generated by EXPLANIN PLAN.

Q: How do you identify that a SQL statement is not optimized?


A: By reading the list plan of execution created by EXPLAIN PLAN.

Q: Describe the EXPLAIN PLAN statement.


A: The EXPLAIN PLAN statement will be used, so that the database will list the plan of
execution.

Q: How do you create the PLAN_TABLE table?


A: If PLAN_TABLE does not exist, run the utlxplan.sql script provided in the
rdbms\admin folder to create the PLAN_TABLE table.

Q: Describe the use of the SET STATEMENT_ID clause.


A: We use the SET STATEMENT_ID clause to identify the plan for later review. We
should have one single unique statement_id for each specific SQL statement that we want
to optimize.

Q: Describe the following operation in PLAN_TABLE.


TABLE ACCESS FULL
TABLE ACCESS BY INDEX
INDEX UNIQUE SCAN
NESTED LOOPS
MERGE JOIN
FILTER
SORT AGGREGATE
A: "SORT GROUP BY" means Oracle will perform a sort on the data obtained for the
user.
"FILTER" means that this is an operation that adds selectivity to a TABLE ACCESS
FULL operation, based on the contents of the where clause.
"NESTED LOOPS" indicates that the join statement is occurring.
"MERGE JOIN" indicates that the join statement is occurring.
"SORT JOIN" indicates that the join statement is sorting.
"TABLE ACCESS FULL" means that Oracle will look at every row in the table
(slowest way).
"TABLE ACCESS BY INDEX" means that Oracle will use the ROWID method to find
a row in the table. It is very fast.
"INDEX UNIQUE SCAN" means Oracle will use the primary or unique key. This is the
most efficient way to search an index.
"SORT AGGREGATE" means Oracle will perform a sort on the data obtained for the
user.

Q: Describe the STATSPACK utility.


A: STATSPACK was created in response to a need for more relevant and more
extensive statistical reporting beyond what was available via UTLBSTAT/UTLESTAT
reports. These statistics can be stored permanently in the database so that historical data
is available for comparison and diagnosis.

Q: How do you install the STATSPACK utility?


A: Create the PERFSTAT user with its objects. Make the TOOLS tablespace as its
default tablespace and the TEMP tablespace as its temporary tablespace. Then, run the
following script. Make sure that you have at least approximately 75 Megabytes of disk
space for the installation.

Q: Describe the SPCREATE script.


A: From this script the PERFSTAT user and its schema (lots of tables, views,
synonyms, packages, etc) will be created.

Q: How do you run the SPCREATE script?


A: SQL> START %ORACLE_HOME%\rdbms\admin\spcreate

Q: Describe the PERFSTAT user.


A: It is a created user to perform the STATSPACK utility.

Q: How do you clean the STATSPACK tables?


A: To clean all the STATSPACK tables, we should run the following script.
SQL> START %ORACLE_HOME%\rdbms\admin\sptrunc
Q: How do you produce a performance report using the STATSPACK utility?
A: SQL> START %ORACLE_HOME%\rdbms\admin\spreport

Q: How do you perform a snapshot in the STATSPACK utility?


A: To take a snapshot, we should execute the following procedure.
SQL> EXECUTE statspack.snap;

Q: Why and how do you set the TIMED_STATISTICS parameter?


A: We set the TIMED_STATISTICS parameter to TRUE to collect timing information
in the V$ view.
SQL> ALTER SYSTEM SET TIMED_STATISTICS=TRUE;

Q: Describe the V$FIXED_TABLE view?


A: You can use the V$FIXED_TABLE view to query information about tables owned
by the SYS user. Normally, they are started with X$, X$_, V$, and V$_.

Q: What is a reasonable snap shots interval for the STATSPACK utility?


A: A 15 minutes in length for each snap shot intervals are reasonable.

Q: What does it mean if an output be represented by #######?


A: If there is output that represented by #######, that indicates that its value is too large
for the STATSPACK column.

Q: What does the Instance Workload Information section contain in the STATSPACK
report output?
A: It contains the Database name, DB ID, Instance name, and tell us the release of our
database, hostname, and the time we started our snap, and ended it with its elapsed time.

Q: What does the Instance Cache Information section contain in the STATSPACK
report utility?
A: It contains the Oracle memory cache information such as the buffer cache, shared
pool, standard block, and log buffer sizes.

Q: What does the Load Profile Information section contain in the STATSPACK report
utility?
A: It contains the load activities during our snapshots such as Redo Size, Logical Reads,
Block Changes, Physical Reads, Physical Writes, etc.

Q: What does the Instance Efficiency Ratios section contain in the STATSPACK report
utility?
A: It contains the system hit ratios. It is very important to keep our eyes on the hit ratios
information, although a database tuning never should be driven by hit ratios. For
example, in a DSS system a low cache hit ratio may be acceptable due the amount of
recycling needed due the large volume of data accessed.
** Instance Efficiency Percentages (Target 100%)
Q: What does the Foreground and Background Wait Events section contain in the
STATSPACK report utility?
A: The Foreground wait events section contains a list of event associated with a session
or client process waiting for a resource such as log file sync, global cache open x, etc. On
the other hand, the Background wait events section contains a list of event associated
with a client process such as latch free, enqueue, row cache lock, etc.
** Order by such that the idle events will be at last. Check the first
record.

Q: What does the Buffer Pool and Buffer Wait Statistics section contain in the
STATSPACK report utility?
A: The Buffer Pool statistics section can have multiple entries if multiple buffer pools
are allocated such as Default, Keep, and Recycle Pools.
In the Buffer Wait Statistics section, we should see a breakdown of each type of object
waited for such as undo header, undo block, data block, segment header, etc.
** Check the ‘Wait’ column ordered by desc.

Q: What does the PGA Memory Statistics section contain in the STATSPACK report
utility?
A: This section contains useful statistics for monitoring session memory usage on
windows servers such as maximum PGA allocated, Total PGA allocated, etc.

Q: What does the ‘Rollback Segment Stats/Storage/Summary for DB’ section contain in
the STATSPACK report utility?
A: The Rollback Segment Stats contains statistics for each segments check the Pct
Waits column and it should be almost zero. If there are not zero that indicates contention
on the segments.
** Watch the Pct Waits column and a high value for "Pct Waits" suggests
more rollback segments may be required.

The Rollback Segment Storage section contains the size of segments. The Undo
Segment Summary contains the description of the V$UNDOSTAT view and shows the
segment status such as unexpired (Stolen, Released, reUsed), or expired (Stolen,
Released, and reused).
** The Optimal Size value should be larger than the Avg Active value.

Q: What does the Latch Activity section contain in the STATSPACK report utility?
A: This section is particularly useful for determining latch contention on an instance.
Latch contention is indicated by a Pct Miss of greater than 1.0% or a relatively high value
in Avg Sleeps/Miss.
** Watch the Pct Miss column.
** "Get Requests", "Pct Get Miss" and "Avg Slps/Miss" are statistics
for willing-to-wait latch get requests
** "NoWait Requests", "Pct NoWait Miss" are for no-wait latch get
requests
** "Pct Misses" for both should be very close to 0.0
Q: What does the Latch Sleep Breakdown and Miss Sources section contain in the
STATSPACK report utility?
A: The Latch Sleep breakdown section contains a list of latches that are candidate of
contentions. Check the Sleeps column. It should be very low. Any positive number in
respect to the Get Requests columns indicates a possible contention. The Miss Sources
section provides a detailed breakdown of which latches are missing and sleeping. Search
on the latch child name experiencing high misses or sleeps and you can often find the bug
responsible.
** ordered by misses descending

Q: What does the Dictionary Cache and Library Cache Statistics section contain in the
STATSPACK report utility?
A: The Dictionary Cache and Library Cache sections contain the Pct Misses column
that should be very low (less than .02). If the column value is more you may have to
increase the shared pool size.
** "Pct Misses" should be very low (< 2% in most cases)

Q: What does the SGA Memory Summary section contain in the STATSPACK report
utility?
A: This section provides a breakdown of how the SGA memory is used at the time of
the report.

Q: What does the SGA Memory Detail section contain in the STATSPACK report
utility?
A: This section shows a detailed breakdown of memory usage (such as java pool free
memory, PX msg pool, Checkpoint queue, KGFF heap, etc) by the SGA at the beginning and
ending of the reporting period.

Q: What does the INIT.ora Parameter Summary section contain in the STATSPACK
report utility?
A: The final section shows the current init.ora parameter settings. It displays those that
are more commonly used including some hidden.

SQL Fundamental Exam Answers


NOTE: The answers go with their sequences. If a question was not answer, that means
that it a repeating question and the answer was given by the previous questions or it is not
in the scope of this subject.

“Nothing in the world can take the place of persistence. Talent will not; nothing
is more common than unsuccessful men with talent. Genius will not; unrewarded
genius is almost a proverb. Educations will not the world is full of educated
derelicts. Persistence and determination alone are omnipotent. The slogan, 'Press
on,' has solved and always will solve the problems of the human race.”

--Calvin Coolidge
Answers:
Q: What are the definitions of the following items?
COLUMN,
RECORD,
TABLE,
ITEM,
FIELD,
ELEMENT,
PRIMARY KEY,
FOREIGN KEY, and
DATATYPE.
A: A column is a smallest unit in a database that you need to deal with. A record is a
collection of columns and a table is a collection of records. The terms: elements,
columns, fields and items can be used interchangeably. A primary key is a unique
identifier in a table. A foreign key is a column in a table (child) that references to a
primary key column in another table (parent). Relationships between two tables are
normally established by defining primary or foreign keys. A datatype is a format that an
input data will be stored in a column.

Q: What is the relationship between primary and foreign keys?


A: Relationships between two tables are normally established by defining primary or
foreign keys. It will establish a child and parent relationships. A foreign key is a column
in a table (child) that references to a primary key column in another table (parent).

Q: Describe the Entity Relationship diagram and Logical Data Model.


A: "Entity Relationship Diagram" or "Logical Data Model" is used to establish
relationships between entities.

Q: What is a composite index?


A: If an index key or a primary key were composed of more than one column. We call
it a composite index.

Q: What are the responsibilities of an Oracle DBA and Oracle Developer?


A: The integrity, security, connectivity, performance, and tuning of a database will be
maintained by DBAs. One of the responsibilities of a DBA is to plan a contingency for
disaster and ensure recovery of the database. On the other hand developers use front-end
and back-end tools along with management tools to perform their tasks. They develop
applications to manipulate a database’s data. Their application will query, insert, delete
and update a record or records. They use front-end tools such as "form builder," "report
builder," and "graphics builder." They use back-end tools such as "schema builder,"
"procedure builder," and "query builder." They use project builder tools to manage and
deliver their applications to their clients.

Q: What is a Database?
A: A collection of all tables under a single or many different schemas can be stored and
maintained in a database. A database, in effect, is a collection of objects such as tables,
indexes, stored procedures, etc.

Q: Query the employee names and their salaries from the employee table.
A: SQL> SELECT ename, sal FROM emp;

Q: Do the above query and use an “as” clause for the “salary” column aliases or column
headings.
A: SQL> SELECT ename, sal AS salary FROM emp;

Q: Repeat the previous query and have “Full Name” for the ename’s column heading
and “Salary” for the “sal” column heading.
A: SQL> SELECT ename “Full Name”, sal "Salary"
FROM emp;

Q: What is the result of 100 + NULL?


A: NULL.

Q: Query the employee names with their commissions.


A: SQL> SELECT ename, comm commission FROM emp;

Q: Use the (NVL) the null value function to assign zero to any null value in the
commission column for the previous query.
A: SQL> SELECT ename, NVL(comm,0) commission
FROM emp;

Q: Concatenate the customers’ last name and first name separated by comma.
A: SQL> SELECT last_name || ', ' || first_name AS "full name"
FROM customers;

Q: Query the employees name sorted by ascending order.


A: SQL> SELECT ename
FROM emp
ORDER BY ename ASC;

Q: Query the employees name sorted by descending order.


A: SQL> SELECT ename FROM emp
ORDER BY ename DESC;

Q: Query the employee information whose employee number is 7788.


A: SQL> SELECT *
FROM emp
WHERE empno = 7788;

Q: Query the employees name whose names start with the letter “M.”
A: SQL> SELECT ename
FROM emp
WHERE ename LIKE 'M%';

Q: Query the employees name whose names end with the letter “R.”
A: SQL> SELECT ename
FROM emp
WHERE ename LIKE '%R';

Q: Query the employees name whose salaries between 2000 and 3000 dollars.
A: SQL> SELECT ename
FROM emp
WHERE sal BETWEEN 2000 AND 3000;

Q: Query the employees name and their department name using the “DECODE”
function. If the department number is 10 then print "accounting.” If the department
number is 20 then print "research," or if the department number is 30 then print "sales."
Anything else prints others.
A: SQL> SELECT ename, DECODE (deptno, 10, 'Accounting',
20, 'Research',
30, 'Sales',
'Others') AS "Department"
FROM emp;

Q: What is an ambiguous column?


A: An ambiguous column is a column that is not defined clearly. Having two tables with
the same column name, you should reference them such that there is no ambiguity on
their ownerships.

Q: How can you resolve an ambiguous column problem?


A: The column name should be identified by alias to make it clear that to what table that
column is belong.

Q: What is a Cartesian product?


A: A “Cartesian” product is caused by joining “N” number of tables while you have less
than “N-1” joins condition in the query.

Q: How can you avoid a Cartesian product?


A: To avoid it, just when joining “N” number of tables you should have more or equal
“N-1” joins condition in the query.

Q: What is an inner join or equi-join?


A: Joining two or more tables together using the WHERE clause with the equal sign (=)
in a query. This type of query will retrieve records that have exact match and will be
called inner join or equi-join.

Q: What is an outer join?


A: Joining two or more tables using OUTER join, not only you retrieve all matching
records but also you retrieve the records that do not match.

Q: What is a self join?


A: When a table refers to itself in the WHERE clause, we call that join is a self-join.

Q: Query all the employee names and their department including all the departments
with no employees.
A: SQL> SELECT ename, dname
FROM emp e, dept d
WHERE e.deptno (+) = d.deptno;

Q: Query the managers’ name with their employees sorted by the manager name.
A: SQL> SELECT mgr.ename “Manager Name”, e.ename “Employee Name”
FROM emp mgr, emp e
WHERE mgr.empno = e.mgr
ORDER BY mgr.ename;

Q: Query the department number and their total, average, min, and max salaries for each
department.
A: SQL> SELECT deptno, SUM(sal), AVG(sal), MIN(sal), MAX(sal)
FROM emp
GROUP BY deptno;

Q: Query the department no and their total salaries that have more than 5 employees
working in their department.
A: SQL> SELECT deptno, SUM(sal)
FROM emp
GROUP BY deptno
HAVING count(*) > 5;

Q: Query the employees name that work for the Research or Sales department (the
department number 20 or 30).
A: SQL> SELECT ename, deptno
FROM emp
WHERE deptno IN (20, 30);

Q: Query the employees name that work in the "accounting" department. Assuming the
department number is unknown.
A: SQL> SELECT ename
FROM emp
WHERE deptno IN
(SELECT deptno
FROM dept
WHERE dname = "ACCOUNTING");

Q: Query the employees name and use the runtime variable to substitute the department
number? Then run it for following department no 10, 20, and 30.
A: SQL> SELECT ename
FROM emp
WHERE deptno = &deptno;
SQL> /

Q: Query the customer names which have more than four orders.
A: SQL> SELECT name
FROM customer c
WHERE exists
(SELECT 'T'
FROM ord
WHERE custid = c.custid
GROUP BY custid
HAVING count(*) > 4);

Q: Create an employee table that contains five columns:


Such as Employee Id, last name, First name, Phone number and Department number with
the following constraints.
1. The last name and first name should be not null.
2. Make a check constraint to check the department number is between 9 and 100.
3. Make a primary constraint on the employee ID column.
4. Make a foreign key on the department number column.
5. Use the "delete cascade" to delete all records if parent gets deleted.
6. Use the "phone number" as a unique key.
A: SQL> CREATE TABLE employee
(empid NUMBER(10),
lastname VARCHAR2(20) not null,
firstname VARCHAR2 (20) not null,
phone_no VARCHAR2 (15),
deptno NUMBER(2) CHECK (deptno BETWEEN 9 AND 100),
constraint pk_employee_01 PRIMARY KEY (empid),
constraint fk_dept_01 FOREIGN KEY (deptno)
references dept (deptno) ON DELETE CASCADE,
constraint uk_employee_01 UNQUE (phone_no));

Q: Create a composite index on the employee table that contains two index columns
(last name and first name).
A: SQL> CREATE INDEX employee_lname_fname_ind_01
ON employee (lastname, firstname);
Q: Query the tables that you as a user own.
A: SQL> SELECT table_name
FROM user_tables
ORDER BY table_name;

Q: Query the index tables that belong to the employee table and owns by the iself user.
A: SQL> SELECT index_name, uniqueness
FROM user_indexes
WHERE table_name = 'EMPLOYEE';

Q: Change the size of the "column_name" to 30 characters logically (for display only).
A: SQL> COLUMN column_name FORMAT a30

Q: Query the indexes columns of the employee table.


A: SQL> SELECT index_name, column_name, column_position
FROM user_ind_columns
WHERE table_name = 'EMPLOYEE';

Q: Insert a record into the "employee" table using column names.


A: SQL> INSERT INTO employee
(empid, lastname, deptno, firstname, phone_no)
VALUES (100, 'smith', 10,'joe', ‘7038212211');

Q: Insert a record using the column position format.


A: SQL> INSERT INTO employee
VALUES (200, 'KING', 'Allen', 5464327532, 10);

Q: How do you save the inserted transaction?


A: COMMIT;

Q: Change the "last_name" column value from “Smith” to “Judd” where the "employee
id" is 100.
A: SQL> UPDATE employee
SET lastname = 'Judd'
WHERE empid = 100;

Q: Delete all the employee records from the "employee" table using the delete command
and the truncate command.
A: SQL> DELETE FROM employee;
OR
SQL> TRUNCATE TABLE employee;

Q: How do you undo a transaction?


A: ROLLBACK;
Q: What is the difference between the delete statement and the truncate statement?
A: Notice that the TRUNCATE command is a DDL statement and all DDL statements
have commit inclusive. That is why the ROLLBACK action after truncation does not
work. Also, if you want to delete all records from a table, you should use the
TRUNCATE statement. It will change the table watermark. The table watermark is an
address that indicates a last location of a record in a table. On the DELETE statement the
watermark will not change. But using the TRUNCATE statement will change the
watermark to the beginning of the table.

Q: Copy the “EMP” table to another table and name the new table "employee." In the
new employee table use the employee name, job, commission and department number.
A: SQL> CREATE TABLE employee
AS SELECT ename, job, comm, deptno
FROM emp;

Q: Add a salary column to the employee table.


A: SQL> ALTER TABLE employee
ADD (salary NUMBER(8,2));

Q: Modify the "ename" column size from varchar10 to varchar15.


A: SQL> ALTER TABLE employee
MODIFY (ename VARCHAR2(15));

Q: Rename the "employee" table to the "iself_employee" table.


A: SQL> RENAME employee TO iself_employee;

Q: Create a view to display the employee names of the “Accounting” department only.
A: SQL> CREATE VIEW employee_name
AS SELECT ename
FROM iself_employee
WHERE deptno = 10;

Q: Why do you use the view?


A: You use view to present rows and columns of a table in the way you want. You may
use it for security reason. For example, you may eliminate some rows and columns that
are very sensitive information. These changes are transparent to a user.

Q: How do you compile the view?


A: SQL> ALTER VIEW employee_name COMPILE;

Q: How do you delete the view?


A: SQL> DROP VIEW employee_name;

Q: Create an index on the employee table on the ename column only and name it
employee_indx.
A: SQL> CREATE INDEX employee_indx
ON employee (ename);

Q: Reorganize the “employee_indx” index table.


A: SQL> ALTER INDEX employee_ indx REBUILD;

Q: Drop the employee_ename index table.


A: SQL> DROP INDEX employee_indx;

Q: Create a user with username “newuser” and password "newpass." Its default
tablespace should be the "iself_data" tablespace.
A: SQL> CREATE USER newuser IDENTIFIED BY by newpass
DEFAULT TABLESPACE iself_data;

Q: Grant the resource and connect roles to newuser.


A: SQL> GRANT resource, connect TO newuser;

Q: Change the newuser password to "mypass".


A: SQL> ALTER USER newuser IDENTIFIED BY mypass;

Q: Can the above new user access to any other user tables?
A: No.

Q: What is a public synonym?


A: It is a synonym that public users can use. We create public synonym so that the
users don’t need to type schema name to a table when they query the table. Creating a
public synonym does not mean that oracle users can access to that table or object. Still
the owner of the object has to grant access to a user on its table.

Q: What is the syntax to create a public synonym?


A: SQL> CREATE PUBLIC SYNONYM employees FOR iself.iself_employee;

Q: What is the difference between public and private synonym?


A: The private synonym is only for the user who owns or created the synonym, but the
public synonym can be used by every users.

Q: Create and drop a private synonym.


A: SQL> CREATE SYNONYM emp_table FOR iself.iself_employee;
To drop:
SQL> DROP SYNONYM emp_table;

Q: Revoke an object privilege on a table from a user.


A: SQL> REVOKE UPDATE, SELECT ON employee FROM newuser;

Q: What does the LIST or ‘L’ command line editor?


A: It lists the current SQL statement that was typed in the Oracle buffer.
Q: What does the INSERT or ‘I’ command line editor?
A: It inserts a command in the Oracle buffer after the current active line that was
indicated with an *.

Q: What does the DEL or ‘D’ command line editor?


A: It deletes the current active line in the Oracle Buffer.

Q: How do you change a string in the Oracle Buffer?


A: First, mark the line as a current active line and then type the‘del’ command.

Q: How do you save the SQL script in the Oracle Buffer?


A: SQL> save c:\myscript.sql

Q: How do you open the SQL Script into the Oracle Buffer?
A: SQL> get c:\myscript.sql

Q: How do you use the notepad editor?


A: Just type: the ed command to open the default editor.

Q: What is afiedt.buf?
A: The "afiedt.buf" file is a place that into which SQL*PLUS stores the most recently
executed SQL statement.

Q: How do you change your text editor in the SQLPLUS tool?


A: Issue the define_editor='your editor' statement from the SQL*PLUS prompt.

Q: What does the ed command in the SQLPLUS tool?


A: We use the "ed" command, to open your default word editor.

Q: Can you have multiple SQL statements in the afiedt.buf file?


A: No. You can only use one SQL statement at a time.

Q: How do you use the notepad editor as an independent tool in the SQLPLUS utility?
A: Just open your notepad editor outside of your SQLPLUS.

Q: How do you execute or run a SQL script?


A: SQL> run c:\myscript.sql or start c:\myscript

Q: What is the SQL ANSI statement?


A: It is some standard roles that provided by American National Standards Institute.

Q: What is the difference between the SQL ANSI statement and Original Oracle
statement?
A: The Original Oracle statements are not follow the role of American National
Standards Institute.
Q: Is the SET command a SQL statement?
A: No.

Q: How do you change your workstation’s page size or line size?


A: SQL> SET LINESIZE 100 PAGESIZE 55

Q: What does the JOIN syntax in the Oracle SQL (DML) statement?
A: It does innor join using the ON clause.
SQL> SELECT ename, dept.deptno, dname
FROM emp JOIN dept
ON emp.deptno = dept.deptno
AND dname <> 'SALES'
/

Q: What is the difference between the JOIN syntax and the NATURAL JOIN syntax?
A: In the NATURAL JOIN syntax, you don't need the ON clause if the column’s names
are the same.

Q: What does the USING clause in the Oracle SQL statement?


A: It joins two tables and in the USING clause the join column names must be the same.

Q: What is the advantage of the NATURAL JOIN syntax?


A: It is less typing.

Q: What does the CROSS JOIN syntax in the Oracle SQL statement?
A: We can use the Oracle9i ANSI standard CROSS JOIN syntax with no
WHERE clause to create a Cartesian product.

Q: What does the IN clause in the Oracle SQL statement?


A: The IN clause in the Oracle SQL statement is an equivalent of the OR condition in
the SQL statement.

Q: What do the OUTER JOIN, RIGHT OUTER JOIN, LEFT OUTER JOIN, and FULL
OUTER JOIN syntax in the Oracle SQL statement?
A: We use the OUTER option when we want all records that have exact match plus
those records that have no match.

Q: How can you perform the FULL OUTER JOIN syntax using the Original Oracle
syntax?
A: Although it is possible but it is very difficult to perform the full outer join using the
original Oracle syntax.

Q: When do you use the WITH … AS clause in the SQL statement?


A: If we have a query which it needs to process the same sub-query several times, we
should consider using the WITH …AS clause in our statement.
Q: How does the WITH … AS clause help your performance?
A: The query will create a temporary table to query it over and over.

Q: Write a query to list all the department names that their total paid salaries are more
than 1/3 of the total salary of the company.
A: SQL> WITH summary_totals AS
(SELECT dname,
SUM(sal) AS totals
FROM emp NATURAL JOIN dept
GROUP BY dname)
SELECT dname, totals
FROM summary_totals
WHERE totals > (SELECT SUM(totals)*1/3
FROM summary_totals)
ORDER BY totals DESC
SQL>/

Q: What are the multiple columns in the SQL statement? Where or how do you use
them?
A: We use multiple columns to match the multiple columns returned from the sub-
query.

Q: Write a SQL statement to query the name of all employees who earn the
maximum salary in their department using the multiple columns syntax.
A: SQL> SELECT deptno, ename, job, sal
FROM emp
WHERE (deptno, sal) IN
(SELECT deptno, MAX(sal)
FROM emp
GROUP BY deptno)
/

Q: What is the inline view in the Oracle SQL statement?


A: If we have a sub-query in a FROM clause in the Oracle SQL statement, is called an
inline view.

Q: Write a SQL statement to query all of the employee names, jobs, and salaries where
their salary is more than 10% of the total company paid salary.
A: SQL> SELECT ename, job, sal
FROM (SELECT ename, job, sal
FROM emp
WHERE sal > (SELECT SUM(sal) * .1
FROM emp)
ORDER BY 3)
/

Q: What does the MERGE statement in the SQL statement?


A: We use the MERGE statement to merge one table into another table.

Q: Can you update, insert, or delete any records while you are using the MERGE
statement?
A: Yes.

Q: What is a Materialized View?


A: A materialized view (MVIEW) is a replica of a target master from a single point in
time.

Q: What are the Materialized View types?


A: Read-Only Materialized Views
Updatable Materialized Views
Sub-query Materialized Views
Row-id vs. Primary Key Materialized Views

Q: Write the difference between ROWID and PRIMARY KEY in the Materialized
View.
A: Fast refresh requires association between rows at snapshot and master sites.
Snapshots that use ROWIDs to refresh are called ROWID snapshots while those that use
primary keys are called primary key snapshots.

Q: What is the difference between a Materialized View and View?


A: A Materialized View is a physical duplicated data in a table, but a View is just a
logical presentation of a table.

Q: When or why do you use a Materialized View?


A: You use Materialized Views to create summaries in a data warehouse environment or
replicate a data in a distributed environment. In data warehouses, you can use
materialized views to pre-compute and store aggregated data such as the sum of sales. In
distributed environments, you can use materialized views to replicate data from a master
site to other distributed sites.

Q: What is a materialized view log?


A: A materialized view log is a holder that contains updated, inserted, or deleted
records’ information in the primary table.

Q: What are the PRIMARY KEY and ROWID in the Materialized View Log?
A: The Materialized View log that use ROWIDs to refresh are called ROWID view log
while those that use primary keys are called primary key view log.

Q: What does the USER_SNAPSHOT_LOGS view contain?


A: It shows if our log was created successfully and its name (MLOG$_EMP).

Q: Create a materialized view that contains the department number, number of


employees, and total salaries paid to employees by department.
A: SQL> CREATE MATERIALIZED VIEW mv_sal
BUILD IMMEDIATE
REFRESH ON DEMAND
AS SELECT deptno,
COUNT(1) AS no_of_emp, SUM(sal) AS salary
FROM emp
GROUP BY deptno
SQL> /

Q: Who can create a materialized view?


A: The one that was granted the CREATE MATERIALIZED VIEW privilege.

Q: What does the USER_MVIEWS view contain?


A: It contains all the Materialized Views’ information that were created by the user.

Q: How do you refresh a materialized view?


A: SQL> EXECUTE dbms_snapshot.refresh('mv_sal','C');

Q: What parameter should be used to update the materialized view every month
automatically without human intervention?
A: The START WITH SYSDATE option will create an immediate data, and the
NEXT(SYSDATE+30) option will update the table every 30 days.

Q: What does the USER_JOBS view contain?


A: It contains all users’ jobs in the Oracle queue.

Q: How do you remove a job from the Oracle Job Queue?


A: SQL> EXECUTE dbms_job.remove(job_number);

Q: How do you drop a materialized view log and a materialized view?


A: SQL> DROP MATERIALIZED VIEW LOG ON emp;
To drop it:
SQL> DROP MATERIALIZED VIEW mv_sal;

Q: What does the BREAK ON clause in SQLPLUS?


A: It builds a break on a column.

Q: What do the REPHEADER and REPFOOTER commands in SQLPLUS?


A: They make a report header and footer.

Q: What does the following commands?


COLUMN sal HEADING 'Salary' FORMAT $99,999.99 --Creates heading format.
COLUMN ename HEADING 'Employee' FORMAT a20 – Creates heading format.
REPHEADER '' – Creates report heading.
BREAK ON dname SKIP 1 – Creates control bread on a column and skip 1 line
after the break.
COMPUTE SUM OF sal ON dname – Computes total salary within a department.
SPOOL c:\salary.out -- Activates spooling.
SPOOL OFF -- Deactivate spooling.
REPFOOTER '' – Creates report footer.
CLEAR BUFFER -- Clear the Oracle buffer.
CLEAR COLUMNS – Clears columns.
CLEAR COMPUTE -- Clears compute functions.

Q: What does the CLEAR command in SQLPLUS?


A: Note that all the values in REPHEADER, REPFOOTER, BUFFER, COLUMNS,
COMPUTE and etc are going to stay the same during your open session. In order to clean
them, you should use the CLEAR command for BUFFER, COLUMNS, and COMPUTE.
And input NULL to REPHEADER and REPFOOTER.

Q: What does the UNION statement in the SQL statement?


A: It will query all the records that match or not match with the base table.

Q: What does the INTERSET statement in the SQL statement?


A: It will query all the records that match with the base table. It is the same as joining
two tables.

Q: What does the MINUS statement in the SQL statement?


A: It will query all the records that are not matching against your base table.

Q: Why it is important to eliminate duplicate records?


A: To keep your database integrity.

Q: What does the following SQL statement?


SQL> DELETE FROM dup_emp
WHERE ROWID IN (SELECT MAX(ROWID)
FROM dup_emp
GROUP BY empno
HAVING COUNT (empno) > 1)
SQL> /
A: Deletes all the rows that have the same employee number except the first one.

Q: What is a data partitioning in the Oracle database?


A: The data partitioning in the Oracle database is that the data will be partitioned in
multi-tablespaces for ease of maintenances.

Q: When should you use data partitioning?


A: When you have a huge data file and can be classified to some partitions.

Q: What is the advantage of using a data partitioning?


A: It is faster to access. It is easier to maintain.

Q: What is a partition key?


A: It is used to separate data and associates them to their own assigned tablespace.

Q: What is a local index in the data partitioning?


A: A Local index is one that is partitioned exactly like the table to which it belongs.

Q: What is a global index in the data partitioning?


A: A Global index, unlike local indexes, you should explicitly partition range
boundaries using the “VALUE LESS THAN” methods.

Q: What are the differences between local and global indexes?


A: In the local index you don’t define explicitly partition range.

Q: How does the ‘VALUE LESS THAN’ method work in the data partitioning?
A: The VALUES LESS THAN clause indicates the partition key value must be less then
its assigned value in order to be illegible for any DML transaction on its assigned
tablespace.

Q: Why do you need multiple tablespaces?


A: Multiple tablespaces give us more flexibility to maintain a tablespace without
affecting any performance or downtime to others.

Q: Create a range-based partitioning table named p_emp. Make sure that the data entry
of the each department goes to its own provided tablespaces such as the accounting
department goes to the dept10ts tablespace, the data entry of the research department
goes to the dept20ts tablespace, etc.
A: SQL> CREATE TABLE p_emp (
empno NUMBER(4) PRIMARY KEY,
ename VARCHAR2(10),
job VARCHAR2(9),
mgr NUMBER(4),
hiredate DATE,
sale NUMBER(7,2),
comm NUMBER(7,2),
deptno NUMBER(2))
STORAGE (INITIAL 5K
NEXT 5K
PCTINCREASE 0)
PARTITION BY RANGE (deptno)
(PARTITION dept10
VALUES LESS THAN (20)
TABLESPACE dept10ts,
PARTITION dept20
VALUES LESS THAN (30)
TABLESPACE dept20ts,
PARTITION dept30
VALUES LESS THAN (40)
TABLESPACE dept30ts,
PARTITION deptxx
VALUES LESS THAN (MAXVALUE)
TABLESPACE deptxxts)
SQL> /

Q: What does the MAXVALUE parameter mean in the data partitioning?


A: It means as large as the column can hold.

Q: How do you analyze a partition table?


A: SQL> ANALYZE TABLE p_emp COMPUTE STATISTICS;

Q: What does the USER_TAB_PARTITIONS view contain?


A: A user can query its partitions table’s information that was created by the user.

Q: Write a query to list the accounting employees from the partition table. Use the
partition option.
A: SQL> SELECT * FROM p_emp PARTITION (dept10);

Q: Write a query to list employee number 7900 from the sales department?
A: SQL> SELECT * FROM p_emp PARTITION (dept30)
WHERE empno = 7900
SQL> /
Q: How do you create a local partition index?
A: SQL> CREATE INDEX p_emp_ind ON p_emp (deptno) LOCAL;

Q: How do you analyze a partition table index?


A: SQL> ANALYZE INDEX p_emp_ind COMPUTE STATISTICS;

Q: What does the USER_IND_PARTITIONS view contain?


A: It contains information in regard to the user’s partition indexes.

Q: What does the ROLLUP operator?


A: The ROLLUP operator returns both ‘regular rows’ and ‘super-aggregate rows.’
Super-aggregate rows are rows that contain a sub-total value.

Q: What does the CUBE function?


A: The CUBE operator returns cross-tabulation values, thus produces totals in all
possible dimensions, and is used for warehousing aggregated data reports.

Q: What are the differences between the CUBE and ROLLUP functions?
A: See the output…

Q: What environments may use the CUBE and ROLLUP functions most?
A: Warehousing.

Q: Write a query to list an aggregation sum report for each job, in each year, using the
ROLLUP grouping option.
A: SQL> SELECT year, job, SUM(sal), COUNT(*)
FROM emp
GROUP BY ROLLUP (year, job)
SQL> /

Q: Write a query to list an aggregation sum report for each job, in each year, using the
CUBE grouping option.
A: SQL> SELECT year, job, SUM(sal), COUNT(*)
FROM emp
WHERE deptno = 20
GROUP BY CUBE (year, job)
SQL> /

Q: What is an object type?


A: The object type in the Oracle database is like the class eliminate in the C++
developer tool or any object oriented tool.

Q: What is a collection object?


A: The collection object in the Oracle database is like a nested table and a variable array
in a table.

Q: Create an object type with two columns to hold the employee's child name and date
of birth and name it employee_kids .
A: SQL> CREATE TYPE employee_kids AS OBJECT (
NAME VARCHAR2(30),
dob DATE
)
SQL> /

Q: Create a table type using employee_kids and name it employee_kids_table.


A: SQL> CREATE TYPE employee_kids_table
IS TABLE OF employee_kids;

Q: Create the emp_family table containing the kid’s column with a type of
employee_kids_table.
A: SQL> CREATE TABLE emp_family
(empno NUMBER,
kids employee_kids_table)
NESTED TABLE kids STORE AS nested_employee_kids_table
SQL> /

Q: How do you insert a record in the object type?


A: SQL> INSERT INTO emp_family VALUES
(7902,
employee_kids_table
(employee_kids('David','08-AUG-01'),
employee_kids('Peter','10-JUN-88'),
employee_kids('Mark','30-OCT-92')
)
)
SQL> /

Q: What is the constructor?


A: The constructor creates an empty nested table as opposed to leaving it null. Notice
that without using the constructor, it is not possible to refer to the nested table with the
"THE" clause.

Q: What is the ‘THE’ sub-query?


A: To query a nested table you should use the "THE" clause. Also, the "THE" sub-query
is used to identify the nested table to INSERT INTO.

Q: How do you query a record using the ‘THE’ sub-query?


A: SQL> SELECT name
FROM
THE(SELECT kids FROM emp_family WHERE empno = 7788)
SQL> /

Q: What is a nested table?


A: It is a table within a table.

Q: How do you insert a record to a nested table?


A: SQL> INSERT INTO
THE(SELECT kids FROM emp_family
WHERE empno = 7900)
VALUES ('Sue','10-DEC-99');

Q: How do you update a record to nested table?


A: SQL> UPDATE emp_family
SET kids = employee_kids_table(
employee_kids('Sara','08-OCT-88'))
WHERE empno = 7788
SQL> /

Q: How do you add a unique index to a nested table?


A: SQL> CREATE UNIQUE INDEX i_nested_employee_kids_table
ON nested_employee_kids_table(nested_table_id,name)
SQL> /

Q: What is a data replica?


A: A duplicated data in a different location.

Q: What is the difference between a materialized view and a materialized view log?
A: The Materialized view is a real duplicated data from a primary table but the
materialized view log is an on going logs generated due to the table changes after the last
refresh.

Q: What is an OID (Object ID)?


A: It is a unique ID assigned to an object by Oracle.
Q: How do you retrieve an object ID?
A: SQL> SELECT OWNER, TYPE_OID FROM DBA_TYPES
WHERE TYPE_NAME LIKE 'ADDRESS%';

Q: How do you use an object ID to create an object type?


A: SQL> CREATE OR REPLACE TYPE address_book_type_object
OID ‘XXXXXXXXXXXXXXXXXXXXX’
AS OBJECT (
id_address NUMBER(1),
address VARCHAR2(20));

Q: What is the relationship between primary and foreign keys?


A: The relationships between two tables are normally established by defining primary or
foreign keys. A primary key has the immutable responsibility of serving as a unique
identifier in a table. A foreign key is a column that refers to the primary key of another
table. To join two tables, a “where clause” is used to set up a table relationship between
primary and foreign keys.

Q: What is a composite index?


A: A primary key can be composed of more than one column. We call it a composite
index.

Q: What is the result of 100 + NULL?


A: NULL value.

Q: Write a query to concatenate the customers’ last name and first name separated by
comma.
A: SELECT last_name || ‘, ‘ || first_name
as “Full Name”
FROM customers
/

Q: Query the employees name and their department name using the “DECODE”
function. If the department number is 10 then print "accounting.” If the department
number is 20 then print "research," or if the department number is 30 then print "sales."
Anything else prints others.
A: SELECT ename, DECODE (deptno, 10, 'Accounting',
20, 'Research',
30, 'Sales',
'Others') AS "Department"
FROM emp
/

Q: Query the department number and their total salaries that have more than 5
employees working in their department.
A: SELECT deptno, SUM(sal)
FROM emp
GROUP BY deptno
HAVING count(*) > 5
/

Q: query the customer names which have more than four orders.
A: SELECT name FROM customer c
WHERE exists (SELECT 'T' FROM ord
WHERE custid = c.custid
GROUP BY custid
HAVING count(*) > 4)
/

Q: Create an employee table that contains five columns:


Such as Employee Id, last name, First name, Phone number and Department number with
the following constraints.
7. The last name and first name should be not null.
8. Make a check constraint to check the department number is between 9 and 100.
9. Make a primary constraint on the employee ID column.
10. Make a foreign key on the department number column.
11. Use the "delete cascade" to delete all records if parent gets deleted.
12. Use the "phone number" as a unique key.
A: CREATE TABLE employee
(empid NUMBER(10),
lastname VARCHAR2(20) not null,
firstname VARCHAR2 (20) not null,
phone_no VARCHAR2 (15),
deptno NUMBER(2) CHECK (deptno BETWEEN 9 AND 100),
constraint pk_employee_01 PRIMARY KEY (empid),
constraint fk_dept_01 FOREIGN KEY (deptno)
references dept (deptno) ON DELETE CASCADE,
constraint uk_employee_01 UNQUE (phone_no))
/

Q: What is the difference between the delete statement and the truncate statement?
A: On the DELETE statement the watermark will not change. But using the
TRUNCATE statement will change the watermark to the beginning of the table.

Q: Copy the “EMP” table to another table and name the new table "employee." In the
new employee table use the employee name, job, commission and department number.
A: CREATE TABLE employee
AS SELECT ename, job, comm, deptno
FROM emp
/

Q: Reorganize the “employee_indx” index table.


A: ALTER INDEX employee_indx REBUILD
/

Q: What is the difference between public and private synonym?


A: You create synonym so that the users don’t need to type schema name to a table
when they query the table. The Public Synonym is available to all database users but the
Private Synonym is available only to the owner of synonym.

Q: Can you have multiple SQL statements in the afiedt.buf file?


A: No.

Q: How do you execute or run a SQL script?


A: SQL> @my_sql_script; or start my_sql_script;

Q: Write a query to list all the department names that their total paid salaries are more
than 1/3 of the total salary of the company.
A: SQL> WITH summary_totals AS
(SELECT dname,
SUM (sal) AS totals
FROM emp NATURAL JOIN dept
GROUP BY dname)
SELECT dname, totals
FROM summary_totals
WHERE totals > (SELECT SUM (totals)*1/3
FROM summary_totals)
ORDER BY totals DESC
SQL>/

Q: What is a Materialized View?


A: A materialized view (MVIEW) is a replica of a target master from a single point in
time. You use Materialized Views to create summaries in a data warehouse environment
or replicate a data in a distributed environment. In data warehouses, you can use
materialized views to pre-compute and store aggregated data such as the sum of sales. In
distributed environments, you can use materialized views to replicate data from a master
site to other distributed sites.

Q: What does the following SQL statement?


SQL> DELETE FROM dup_emp
WHERE ROWID IN (SELECT MAX(ROWID)
FROM dup_emp
GROUP BY empno
HAVING COUNT (empno) > 1)
SQL> /
A: Deletes duplicated records.
Q: What does the MAXVALUE parameter mean in the data partitioning?
A: It is the maximum possible value that can be store into a column.

Q: What does the following SQL statement?


SQL> INSERT INTO THE(SELECT kids FROM emp_family
WHERE empno = 7900)
VALUES ('Sue','10-DEC-99')
SQL> /
A: Inserts a record to a nested object in a table.

Oracle 10g Fundamental Exam Answers

NOTE: The answers go with their sequences. If a question was not answer, that means
that it a repeating question and the answer was given by the previous questions or it is not
in the scope of this subject.

“Happiness is when what you think, what you say, and what you do are in harmony.”

Mahatma Gandhi

Answers:

Regular Expression

Q: What is Regular Expression (REGEXP) in the Oracle 10g Database?

A: It is a method for simple and complex patterns for searching and manipulating a text.
You can search, extract, format, and manipulate a text in the database. At the beginning,
it appears that the syntax is not very intuitive but by second look, it may look easy. The
technique more reflects as UNIX style regular expressions.

Q: What are functions of REGEXP?


A: Interfaces: Oracle Regular Expressions are implemented by the following functions
available in SQL and PL/SQL.

REGEXP_LIKE ,
*

REGEXP_REPLACE ,
*

REGEXP_INSTR , and
*

REGEXP_SUBSTR

Q: What are the Metacharacters in REGEXP?

Metacharacters: The following is a list of supported Oracle metacharacters use in Oracle


Regular Expressions.

Syntax

Description

Classification

Match any character

Dot

a?

Match ‘a’ zero or one time


Quantifier

a*

Match ‘a’ zero or more time

Quantifier

a+

Match ‘a’ one or more time

Quantifier

a|b

Match either ‘a’ or ‘b’

Alternation

a{m}

Match ‘a’ exactly m times

Quantifier

a{m,}

Match ‘a’ at least m times

Quantifier

a{m,n}
Match ‘a’ between m and n times

Quantifier

[abc]

Match either ‘a’ or ‘b’ or ‘c’

Bracket Expression

(…)

Group an expression

Subexpression

\n

Match nth subexpression

Backreference

[:cc:]

Match character class in bracket expression

Character Class

[.ce.]

Match collation element in bracket expression

Collation Element

[=ec=]
Match equivalence class in bracket expression

Equivalence Class

Q: What are the Character Classes?

A: Character Classes: They are sensitive to the underlying character set such as the
[:lower:] character class.

The following is a list of Oracle supports character classes , based on character class
definitions in NLS classification data:

Character Class Syntax

Meaning

[:alnum:]

All alphanumeric characters

[:alpha:]

All alphabetic characters

[:blank:]

All blank space characters.

[:cntrl:]

All control characters (nonprinting)


[:digit:]

All numeric digits

[:graph:]

All [:punct:], [:upper:], [:lower:], and [:digit:] characters.

[:lower:]

All lowercase alphabetic characters

[:print:]

All printable characters

[:punct:]

All punctuation characters

[:space:]

All space characters (nonprinting)

[:upper:]

All uppercase alphabetic characters

[:xdigit:]

All valid hexadecimal characters

Q: Consider a simple query to convert the ‘McLean’ city name to a more readable
format (Mc Lean). You should look for any instance for a lower case letter immediately
followed by an upper case letter. Your query should record these two letters in
backreferences by using subexpressions, then replaces the first one, followed by a space,
then followed by the second letter.

A:

SQL> SELECT

REGEXP_REPLACE (‘McLean’,

‘([[:lower:]])([[:upper:]])’, ‘\1 \2’) as “City”

FROM dual;

Q: How to use REGULAR EXPRESSIONS in Oracle

A: Keep this in your mind that these functions support CHAR, VARCHAR2, CLOB,
NCHAR, NVARCHAR, and NCLOB datatypes.

Q: What does the REGEXP_LIKE function?

A: It returns a Boolean indicating whether the pattern matched or not.

Q: Consider to write an expression that could search for common inflections of the verb
‘try’.

A: The following regular expression will match try, trying, tried, and tries.

SQL> SELECT

REGEXP_LIKE (‘We are trying to make the subject easier.’,

‘tr(y(ing)? | (ied) | (ies))’) as REGEXT_SAMPLE

FROM dual;

Q: What does the REGEXP_SUBSTR function?

A: It returns the actual data that matches the specified pattern.


Q: Consider to write an expression that could return the ‘trying’ specified pattern.

A:

SQL> SELECT

REGEXP_SUBSTR (‘We are trying to make the subject easier.’,

‘tr(y(ing)? | (ied) | (ies))’) as REGEXT_SAMPLE

FROM dual;

Q: What does the REGEXP_INSTR function?

A: It returns the character position of either the beginning or end of the match.

Q: Consider to write an expression that could return the position of ‘trying’ specified
pattern.

A:

SQL> SELECT

REGEXP_INSTR (‘We are trying to make the subject easier.’,

‘tr(y(ing)? | (ied) | (ies))’) as REGEXT_SAMPLE

FROM dual;

Q: What does the REGEXP_REPLACE function?

A: It looks for an occurrence of a regular expression and replaces it with the contents of
a supplied text literal.

Q: Query a list of all employees’ name that hired between 1996 and 1999.
A:

SQL> SELECT ename FROM emp

WHERE REGEXP_REPLACE

(TO_CHAR(hire_date, ‘YYYY’), ‘^199[6-9]$’);

You used ‘^’ to indicate that the beginning of the line has to be 199, and [-] with $ to
specify range of valid characters.

Q: What is occurrence in the REGEXP functions?

A: All functions take an occurrence that specifies you require the nth matching
expression in REGEXP_SUBSTR and REGEXP_INSTR , the default for which is 1.

Q: Consider extracting the third field being the Oracle system identification in a column.

A:

SQL> SELECT

REGEXP_SUBSTR (‘system/password@myhost:1521:mysid’,

‘[^:]+’, 1, 3) as “SID name”

FROM dual;

UNDO Advisor

Q: What is the UNDO advisor?


A: You can size your UNDO tablespace with the UNDO Advisor . The Snapshot Too
Old error will be noted in the database alert history. Assuming that the UNDO tablespace
is UNDOTBS1, to check the time and problem on the UNDO tablespace do the
following.

SQL> SELECT time_suggested, reason

FROM dba_alert_history

WHERE object_name = ‘UNDOTBS1’

You can use the Database Control home page to utilize the UNDO Advisor to get
recommendations to correct the problem. From the Database Control home page, click on
the Administration tab and then UNDO Management. On that page change the Analysis
Time Period field to Last One Hour and click the Update Analysis button. Now, you
should see a recommendation from UNDO Advisor. You should be able also to change
the size and apply the changes.

Q: How do you check the time and problem on the UNDO tablespace ?

A:

SQL> SELECT time_suggested, reason

FROM dba_alert_history

WHERE object_name = ‘UNDOTBS1’

To correct the problem: You can use the Database Control home page to utilize the
UNDO Advisor to get recommendations to correct the problem. From the Database
Control home page, click on the Administration tab and then UNDO Management. On
that page change the Analysis Time Period field to Last One Hour and click the Update
Analysis button. Now, you should see a recommendation from UNDO Advisor. You
should be able also to change the size and apply the changes.

The Oracle Data Pump Export and Import utilities

Q: Why do you use Data Pump Export and Import?


A: The expdp and impdp tools support all the original exp and imp functionalities plus
many new features. With previous release, you could only move the transportable
tablespace across Oracle databases that were running on the same architecture and
operating system. With Data Pump , you are able to transport data files from one
plateform to another. Only you have to make sure that both source and target databases
set their COMPATIBLE initialization parameter to 10.0.0 or greater.

Q: Export the DEPT and EMP records that deptno is 10 or 30 from the ISELF schema.

A:

# expdp

FILE=/u02/oradata/ora10g/EXPDAT02.DMP

FILESIZE=2048M

LOG= /u02/oradata/ora10g/EXPDAT.LOG

TABLES=ISELF.CUSTOMER,ISELF.DEPT,ISELF.EMP

GRANTS=y

INDEXES=y

ROWS=y

CONSTRAINTS=y

CONSISTENT=n

RECORD=n

QUERY='WHERE deptno IN (10, 30)'

Q: Export the iself, outln and system schemas.

A:

# expdp
FILE=/u02/oradata/ora10g/EXPDAT05.DMP

FILESIZE=2048M

LOG= /u02/oradata/ora10g/EXPDAT.LOG

OWNER=ISELF,OUTLN,SYSTEM

GRANTS=y

INDEXES=y

ROWS=y

CONSTRAINTS=y

CONSISTENT=n

RECORD=n

Q: How do you import the DEPT and EMP tables with recalculating statistics and
committing after each array insert?

A:

# impdp

FILE=/u02/oradata/ora10g/EXPDAT.DMP

LOG= /u02/oradata/ora10g/IMPORT.LOG

FROMUSER=iself

TABLES=emp,dept

GRANTS=y

INDEXES=y

ROWS=y

CONSTRAINTS=y

IGNORE=y
COMMIT=y

RECALCULATE_STATISTICS=y

DATAFILES=n

Q: Perform a Parallel Full Export on the DIR1, DIR2 directory objects and make sure
that each file be 2 GB in size.

A:

$ expdp

FULL=y

PARALLEL=2

DUMPFILE=DIR1:exp1%U.dmp, DIR2:exp2%U.dmp

FILESIZE=2G

The %u implies that multiple files may be generated and start at 01 with a two-digital
number.

Q: Export only all functions, tables, procedures (proc1 and proc2 only), and all views
that starts with the ‘EMP’ characters from the iself and SCOTT schemas.

A:

$ expdp

SCHEMAS=iself,scott

DIRECTORY=private_exp_space

DUMPFILE=expdat01.dmp

INCLUDE=function

INCLUDE=table
INCLUDE=procedure:”in (‘proc1’,’proc2’)”

INCLUDE=view:”like ‘EMP%’”

Either you should use INCLUDE or EXCLUDE.

Q: Generate a SQL script from an existing export dump file.

A:

$ impdp

DIRECTORY=private_exp_space

DUMPFILE=expdat01.dmp

SQLFILE=MyScript.sql

Q: Move objects from one tablespace to another by using the REMAP_TABLESPACE


option.

A:

$ impdp

SCHEMAS=iself

REMAP_TABLESPACE=iself_tablespace:urself_tablespace

Q: How can you read from your exported file directly without importing them into your
database?

A:

SQL> CREATE TABLE external_emp

(ename, sal, comm)

ORGANIZATION EXTERNAL
(

TYPE ORACLE_DATAPUMP

DEFAULT DIRECTORY private_exp_space

LOCATION ( ‘expdat01.dmp’)

PARALLEL AS

SELECT ename, sal, comm.

FROM emp WHERE deptno IN (10, 30);

Q: What is an endian format?

A: The endian format or Byte ordering is a format that will affect the results when data
is written and read. For example, the 2-bytes integer value 1 is written as 0x0001 on a
big-endian system and as 0x0100 on a little-endian system. To determine the endian
format of a platform do the following query:

SQL> SELECT p.endian_format

FROM v$transportable_platform p, v$database d

WHERE p.platform_name = d.platform_name

The v$transportable_platform view contains all supported platforms. In order to convert


form one platform to another platform uses the rman utility. The following is an example
of how to convert from one platform to another.

$ rman TARGET=/

RMAN> CONVERT DATAFILE ‘/local/oradata/school/*’

FROM PLATFORM = ‘Solari [tm] OE (32-bit)’

DB_FILE_NAME_CONVERT =

‘/local/oradata/school/data’ , ‘/remote/oradata/data’;
Backup and Recovery Enhancements

Q: What is the Flash Recovery Area ?

A: It is a unified storage location for all recovery-related files and activities in an Oracle
Database. It includes Control File, Archived Log Files, Flashback Logs , Control File
Autobackups, Data Files, and RMAN files.

Q: How do you define a Flash Recovery Area ?

A: To define a Flash Recovery Area set the following Oracle Initialization Parameters.

SQL> ALTER SYSTEM SET db_recovery_file_dest_size = 100G;

SQL> ALTER SYSTEM SET db_recovery_file_dest = ‘/u10/oradata/school’;

Q: How do you use the V$RECOVERY_FILE_DEST view to display information


regarding the flash recovery area?

A:

SQL> SELECT name, space_limit, space_used,

space_reclaimable, number_of_files

FROM v$recovery_file_dest;

Q: How can you display warning messages?

A:
SQL> SELECT object_type, message_type,

message_level, reason, suggested_action

FROM dba_outstanding_alerts ;

Q: How do you backup the Flash Recovery Area ?

A:

RMAN> BACKUP RECOVERY FILES;

The files on disk that have not previously been backed up will be backed up. They are
full and incremental backup sets, control file auto-backups, archive logs, and datafile
copies.

Q: How to use the best practice to use Oracle Managed File (OMF) to let Oracle
database to create and manage the underlying operating system files of a database?

A:

SQL> ALTER SYSTEM SET

db_create_file_dest = ‘/u03/oradata/school’;

SQL> ALTER SYSTEM SET

db_create_online_dest_1 = ‘/u04/oradata/school’;

Q: How to enable Fast Incremental Backup to backup only those data blocks that have
changed?

A:

SQL> ALTER DATABASE enable BLOCK CHANGE TRACKING;


Q: How do you monitor block change tracking?

A:

SQL> SELECT filename, status, bytes

FROM v$block_change_tracking ;

It shows where the block change-tracking file is located, the status of it and the size.

Q: How do you use the V$BACKUP_DATAFILE view to display how effective the
block change tracking is in minimizing the incremental backup I/O?

A:

SQL> SELECT file#, AVG(datafile_blocks), AVG(blocks_read),

AVG (blocks_read/datafile_blocks), AVG(blocks)

FROM v$backup_datafile

WHERE used_change_tracking = ‘YES’ AND incremental_level > 0

GROUP BY file#;

If the AVG (blocks_read/datafile_blocks) column is high then you may have to decrease
the time between the incremental backups.

Q: How do you backup the entire database?

A:

RMAN> BACKUP DATABASE ;

Q: How do you backup an individual tablespaces?

A:

RMAN> CONFIGURE DEFAULT DEVICE TYPE TO DISK;


RMAN> BACKUP TABLESPACE system;

Q: How do you backup datafiles and control files?

A:

RMAN> BACKUP DATAFILE 3;

RMAN> BACKUP CURRENT CONTROLFILE;

Q: Use a fast recovery without restoring all backups from their backup location to the
location specified in the controlfile.

A:

RMAN> SWITCH DATABASE TO COPY;

RMAN will adjust the control file so that the data files point to the backup file location
and then starts recovery.

Q: How can you begin and end backup on the database level?

A:

SQL> ALTER DATABASE BEGIN BACKUP ;

Copy all the datafiles…

SQL> ALTER DATABASE END BACKUP;

Q: How do you set the flash recovery area?

A:

SQL> ALTER SYSTEM SET db_recovery_file_dest_size = 100G;

SQL> ALTER SYSTEM SET db_recovery_file_dest = ‘/u10/oradata/school’;


Q: How do you gather information regarding the flash recovery area?

A:

SQL> SELECT name, space_limit, space_used,

space_reclaimable, number_of_files

FROM v$recovery_file_dest;

The Flashback feature

Q: What is the flashback?

A: The flashback gives users the capability to query past version of schema objects,
query historical data, and perform change analysis.

Q: How it works?

A: Every transaction logically generates a new version of the database. You can
navigate through these versions to find an error and its cause.

Q: Why do need to use the flashback?

A: It eliminates restore process and it is faster than traditional point-in-time recovery.

Q: What is its architecture?

A: Now, one more log was added as Flashback Database log. The Oracle database
server regularly logs before images of data blocks in the Flashback Database logs from
Flashback buffer in the SGA Oracle memory. The Flashback Database must be enabled.
When it is enabled, the new RVWR (Recovery Version Writer) background process will
be started. The RVWR background process sequentially writes Flashback Database data
from the flashback buffer to the Flashback Database logs which are circularly reused.
Q: How do you configure Flashback Database?

A:

Assuming:

The database is in archive mode.

The database flash recovery area was configured.

Set the database flashback retention time target.

SQL> ALTER SYSTEM SET db_flashback_retention_target = 2880; -- Ex: for two


days.

Enable Flashback Database. Before altering your database, the database must be in
MOUNT EXCLUSIVE mode, ARCHIVELOG mode, and the Flashback be enabled. To
check whether it is enable do the following SQL statement.

SQL> SELECT flashback_on FROM v$database ;

SQL> ALTER DATABASE FLASHBACK ON;

If you disable the flashback (OFF), all existing Flashback Database logs are deleted
automatically.

Q: How do you Flashback a database?

A: The FLASHBACK DATABASE command force the database back to a past time or
SCN. See the following examples:

SQL> FLASHBACK DATABASE TO TIMESTAMP (sysdate-5/24); -- Go back 5


hours from now.

SQL> FLASHBACK DATABASE TO SCN 65473;

Q: How do you monitor Flashback Database?


A: Use the V$FLASHBACK_DATABASE_LOG view to display the approximate
lowest SCN and time to which you can flash back your database.

SQL> SELECT oldest_flashback_scn, oldest_flashback_time

FROM v$flashback_database_log;

Q: How do you use the V$FLASHBACK_DATABASE_LOG view to determine how


much disk space is needed to meet the current flashback retention target?

A:

SQL> SELECT estimated_flashback_size, flashback_size

FROM v$flashback_database_log;

Q: How do you use the V$FLASHBACK_DATABASE_STAT view to monitor the


overhead of logging flashback data?

A: You can use this to adjust the retention time or the flash recovery area size.

SQL> SELECT * FROM v$flashback_database_stat;

Q: How do you exclude a tablespace from flashback database?

A: If you do not want the USER tablespace to be included to log Flashback Database
data, do the following SQL statement.

SQL> ALTER TABLESPACE users FLASHBACK OFF;

Q: When are you not able to Flashback Database?

A:

The control file has been restored or recreated,


*
A tablespace has been dropped,
*

A data file has been shrunk, and


*

A RESETLOSG operation is required.

Q: How can you query the content of the recycle bin by using the DBA_RECYCLEBIN
view?

A:

SQL> SELECT * FROM dba_recyclebin WHERE can_undrop = ‘YES’;

SQL> SHOW RECYCLEBIN

Q: How do you restore from recycle bin?

A: Use the FLASHBACK TABLE command to recover a table and all its possible
dependent objects form the recycle bin.

SQL> DROP TABLE iself.emp;

SQL> SELECT original_name, object_name, type, ts_name,

dropttime, related, space

FROM dba_recyclebin

WHERE original_name = ‘EMP’;

SQL> FLASHBACK TABLE emp TO BEFORE DROP;

SQL> FLASHBACK TABLE emp

TO BEFORE DROP RENAME TO employee;

SQL> FLASHBACK TABLE emp

TO TIMESTAMP to_timestamp (’14:45’,’HH24:MI’);


Q: How do you reclaim the recycle bin?

A: By using PURG option.

SQL> PURGE TABLE emp; -- Purges the specified table.

SQL> PURGE TABLESPACE scott_ts USER scott; -- All the Scott’s objects.

SQL> PURGE RECYCLEBIN ; -- Purges all user objects.

SQL> PURGE DBA_RECYCLEBIN ; -- Purges all the objects.

Q: How can you perform queries on the database as of a certain clock time or SCN?

A:

SQL> SELECT versions_xid, sal, versions_operation

FROM emp

VERSIONS BETWEEN TIMESTAMP sysdate-10/24 AND sysdate

WHERE empno = 100;

Q: How can you use the CURRENT_SCN column in the V$DATABASE view to
obtain the current SCN?

A:

SQL> SELECT current_scn FROM v$database ;

Q: How can you enforce to guaranteed UNDO retention?

A: You can do one of the following SQL statements.

SQL> CREATE UNDO TABLESPACE my_undotbs1


DATAFILE ‘my_undotbs01.dbf’ SIZE 10G AUTOEXTEND ON

RETENTION GUARANTEE;

SQL> ALTER TABLESPACE my_undotbs1

RETENTION GUARANTEE;

Q: How can you check the UNDO retention?

A:

SQL> SELECT tablespace_name, retention FROM dba_tablespaces;

Q: How can you recover deleted file?

A:

Connect as sysdba and flashback the table.

SQL> CONNECT / AS SYSDBA

Use the FLASHBACK TABLE command to recover a table and all its possible
dependent objects form the recycle bin.

Check what do you have in your recycle bin.

SQL> SELECT original_name, object_name, type, ts_name,

dropttime, related, space

FROM dba_recyclebin

WHERE original_name = ‘FLASHBACK_TABLE’

SQL> FLASHBACK TABLE iself.emp TO BEFORE DROP;

Q: How do you test that your recovery was successful?


A:

SQL> SELECT count(*) FROM flashback_table;

Automatic Database Diagnostic Monitor

Q: What does the Automatic Database Diagnostic Monitor ?

A: The Automatic Database Diagnostic Monitor (ADDM ) maintains a self-diagnostic


to a database. It will either perform a treatment or refer it to specialists such as the SQL
tuning advisor.

Q: How does ADDM work?

A: The Oracle database automatically gathers statistics from the SGA every 60 minutes
and stores them in the Automatic Workload Repository (AWR ) in the form of
snapshots. These snapshots are similar to STATSPACK snapshots. The MMON process,
it is a process that schedules the ADDM to run automatically to detect problems
proactively for every two last snapshots. It is possible also to invoke an ADDM analysis
manually.

Q: Where can I access the latest ADDM run?

A: Go to the Database Control home page, on the Diagnostic Summary section you will
see the number of ADDM finding from the previous automatic run. Click on the
Performance Findings link. The Automatic Database Diagnostic Monitor (ADDM) page
will be display with the details of the latest ADDM run.

Q: How can I turn the ADDM process off?

A: By default the ADDM process is enabled since the STATISTICS_LEVEL


initialization parameter is TYPICAL. By setting these parameters to BASIC, it will stop
to run automatically.

Q: How can you check your ADDM default setting?


A: Execute the following SQL statement.

SQL> SELECT parameter_value, is_default

FROM dba_advisor_def_parameters

WHERE advisor_name = ‘ADDM ’

Q: How can I retrieve ADDM Reports using SQL?

A: You should type the following SQL statement to display the most recent ADDM
report using a SQL command.

SQL> SELECT dbms_advisor .GET_TASK_REPORT(task_name)

FROM dba_advisor_tasks

WHERE task_id = (SELECT max(t.task_id)

FROM dba_advisor_tasks t, dba_advisor_log l

WHERE t.task_id = l.task_id AND t.advisor_name = ‘ADDM ’

AND l.status = ‘COMPLETED’

or

SQL> @$ORACLE_HOME/rdbms/addmrpt

Q: What is the Automatic Shared Memory Management (MMAN )?

A: It maintains the management of the most important shared memory structures. For
example, if your system runs OLTP during the day and large parallel batch jobs at night,
you may not need to decrease buffer cache and increase large pool in order to satisfy the
needs of your nightly jobs. The MMAN background process should do that.
Q: How do you enable or disable Automatic Shared Memory Management ?

A: Go to your Database Control page. Click on the Administration tab, select Memory
Parameters under the Instance heading, and click the SGA tab. Now, you are able to
enable or disable. When you enable it, you can enter the total SGA size or the
SGA_TARGET value. If you set SGA_TARGET to 0, Automatic Shared Memory
Management will be disabled.

Q: How do you determine the actual size of the auto-tuned components in the SGA?

A: When the SGA_TARGET value is set to no-zero, you can determine the actual size
of the auto-tuned components in the SGA by the following SQL statement.

SQL> SELECT component, current_size/1024/1024

FROM v$sga_dynamic_components

Notice that if the SGA_TARGET value is no-zero and no value for an auto-tuned SGA
parameter, then the values of the auto-tuned SGA parameters in the v$parameter view is
0. You will see the values if you assigned a value for any of the auto-tuned parameters.

SQL> SELECT name, value, isdefault

FROM v$parameter

WHERE name LIKE ‘%size’

Q: How do you change the SGA_TARGET value?

A: You can change it by using the ALTER SYSTEM command dynamically. The value
can be increased up to the value of SGA_MAX_SIZE .

Q: What is Automatic Checkpoint Tuning?


A: It will make the best effort to write out dirty buffers without adverse impact on the
database automatically. To enable it you should set the FAST_START_MTTR_TARGET
value to a nonzero value and all the checkpoint parameters will be ignored.

Oracle Manageability Infrastructure

Q: What are the components of Oracle manageability Infrastructure?

A: Automated tasks

Server-Generated alerts

Advisory Framework

Automatic Workload Repository

Q: Describe Automatic Routine Administration tasks:

A: You can use the Scheduler , to submit a task that needs to be performed for keeping
the database in tune. To add a task, go to the Database Control home page, click on the
Administration tab, click the Jobs link in the Scheduler section, and then create the task.
You may add a task using PL/SQL. See the following example: Assuming that you have
already created the ONLINE_BKUP procedure to perform online backup. You now want
to add that task to the WEEKEND_WINDOW.

SQL> BEGIN

DBMS_SCHEDULER .CREATE_JOB (

Job_name => ‘online_bkup’,

Job_type => ‘STORED_PROCEDURE’,

Job_action => ‘myonline_backup’,

Job_class => ‘AUTO_TASKS_JOB_CLASS ’,

Scheduler _name=> ‘WEEKEND_WINDOW’);


END;

Q: Describe Server-Generated alerts :

A: If a problem was detected, the Oracle server will send an (email) alert message with
possible corrective actions. The difference between Enterprise Manager Alerts and
Server-Generated alerts is mainly that the metrics threshold validations are performed by
MMON, which unlike Enterprise Manager should access SGA. These alerts appear in
DBA_OUTSTANDING_ALERTS and, when cleared, they go to
DBA_ALERT_HISTORY. To set alert thresholds, go to database home page, click
Manage Metrics in the Related links section. Then click the Edit Thresholds button. You
can also use the DBMS_SERVER_ALERT .SET_THRESHOLD procedure. For
example:

SQL> BEGIN

DBMS_SERVER_ALERT .SET_THRESHOLD (

DBMS_SERVER_ALERT .CPU_TIME_PER_CALL,

DBMS_SERVER_ALERT .OPERATOR_GE, ‘8000’,

DBMS_SERVER_ALERT .OPERATOR_GE, ‘10000’, 1, 2, ‘school’,

DBMS_SERVER_ALERT .OBJECT_TYPE_SERVICE, ‘payroll’);

END;

Q: Describe Advisory Framework :

A: They are server components that provide a DBA with useful feedback about a
database resource utilization and performance. The following are the list of advisors:
ADDM , SQL Tuning Advisor, SQL Access Advisor , PGA Advisor, SGA Advisor,
Segment Advisor , and UNDO Advisor . To open the Advisors Central page, go to the
Database Control home and click on the Advisor Central link in the list of Related Links.
The DBMS_ADVISOR package contains all constants and procedure declarations you
need for all advisors. There are Advisor views such as DBA_ADVISOR_{TASKS | LOG
| OBJECTS | RECOMMENDATIONS | ACTIONS}.

Q: What is Automatic Workload Repository (AWR )?

A: It provides services to Oracle components to collect, maintain, process, and access


performance statistics for problem detection and self-tuning purposes. The MMON
(Manageability Monitor) background process will transfer the memory version of the
statistics every 60 minutes to disk on a regular basis and MMNL (Manageability Monitor
Light) whenever the buffer is full. The workload repository resides in the SYSAUX
tablespace . A baseline can be identified by executing the
DBMS_WORKLOAD_REPOSITORY.CREATE_BASELINE procedure. To run
Automatic Workload Repository Reports run the following SQL script.

SQL> @$ORACLE_HOME/rdbms/admin/awrrpt

Q: Manually invoke the ADDM advisor to analyze the database between snapshots 60
and 66. Then, use the task name to get the results from the analysis

A: Define a binding variable to hold the task name and another variable to hold task id.

SQL> VARIABLE tname VARCHAR2 (60)

SQL> VARIABLE taskid NUMBER

Create an advisor task of the particular ADDM type.

SQL> EXEC dbms_advisor .create_task(‘ADDM ’, :taskid, :tname);

Set the required parameters to run this specific type of task.

SQL> EXEC dbms_advisor .set_task_parameter(:tname, ‘START_SNAPSHOT’, 60);

SQL> EXEC dbms_advisor .set_task_parameter(:tname, ‘END_SNAPSHOT’, 66);

Execute the task.

SQL> EXEC dbms_advisor .execute_task(:tname);

Use the task name to get the results from the analysis.

SQL> SELECT dbms_advisor .get_task_report(:tname)


FROM dba_advisor_tasks t

WHERE t.task_name = :tname AND

t.owner = SYS_CONTEXT (‘userenv’, ‘session_user’)

Q: As sysdba, create a special procedure to de-queue alert information from the


ALERT_QUE. Then give an object privilege to SYSTEM to use it.

A: Logging into SQL*PLUS as sysdba

SQL> CONNECT / as sysdba

Add a new subscriber ALERT_MYUSERS to the internal ALERT_QUE queue.

SQL> EXEC dbms_aqadm .add_subscriber (

‘SYS.ALERT_QUE’, AQ$_AGENT(‘ALERT_MYUSERS’,’’,0));

Grant user SYSTEM the right to dequeue from the ALERT_QUE.

SQL> BEGIN

dbms_aqadm .enable_db_access(

agent_name=>’ALERT_MYUSERS’,db_username=>’SYSTEM’);

END;

SQL> BEGIN

dbms_aqadm .grant_queue_privilege (

Privilege=>’DEQUEUE’,

queue_name=>’ALERT_QUE’,

Grantee=>’SYSTEM’);

END;
Now, write a Stored PL/SQL procedure that is used by user SYSTEM to dequeue alert
information from the ALERT_QUE.

SQL> CREATE OR REPLACE PROCEDURE my_dequeue IS

dequeue_options dbms_aq.dequeue_options_t;

message_properies dbms_aq.message_properties_t;

message ALERT_TYPE;

message_handle RAW(16);

BEGIN

dequeue_options.consumer_name := ‘ALERT_MYUSERS’;

dequeue_options.wait := dbms_aq.no_wait;

dequeue_options.naviagtion := dbms_aq.first_message;

dequeue_options.dequeue_mode := dbms_aq.remove;

dbms_aq.dequeue (

queue_name => ‘SYS.ALERT_QUE’,

dequeue_options => dequeue_options,

message_properties => message_properties,

payload => message,

msgid => message_handle);

Dbms_output.put_line(‘This is my alert message dequeue…’);

END;

Grant ‘EXECUTE’ object privilege on MY_DEQUEUE to SYSTEM.

SQL> GRANT EXECUTE ON MY_DEQUEUE TO SYSTEM;


Q: Set the USER Commits Per Sec metric with a warning threshold set 3, and a critical
threshold set to 7. Your observation period should be for one minute, and the number of
consecutive occurrences should be set to two.

A:

SQL> BEGIN

DBMS_SERVER_ALERT .set_threshold (

DBMS_SERVER_ALERT .user_commits_sec,

DBMS_SERVER_ALERT .operator_ge, 3,

DBMS_SERVER_ALERT .operator_ge, 7,

1,2, ‘school’,

DBMS_SERVER_ALERT .object_type_system, null);

END:

Check that the metrics thresholds have been set.

SQL> COL object_name FORMAT a30

SQL> COL metrics_name FORMAT a30

SQL> COL warning_value FORMAT a10

SQL> COL critical_value FORMAT a10

SQL> SELECT object_name, metrics_name, warning_value, critical_value

FROM dba_thresholds;

Q: How do you examine your outstanding alerts and alert history?

A:

SQL> SELECT reason FROM dba_outstanding_alerts ;

SQL> SELECT reason FROM dba_alert_history


WHERE upper(reason) like ‘%COMMIT%’

ORDER BY creation_time desc

Q: How to clean up your threshold set up?

A: Do the following statement as sysdba. Set threshold values to NULL.

SQL> BEGIN

DBMS_SERVER_ALERT .set_threshold (

DBMS_SERVER_ALERT .user_commits_sec,

NULL,

NULL,

NULL,

NULL,

1, 1, ‘SCHOOL’,

DBMS_SERVER_ALERT .object_type_system, NULL);

END;

Q: How do you disable your ALERT_MYUSER and remove subscriber?

A:

SQL> EXEC dbms_aqadm .disable_db_access(‘ALERT_MYUSER’,’SYSTEM’);

SQL> BEGIN

dbms_aqadm .remove_subscriber(
‘SYS.ALERT_QUE’,AQ$_AGENT(‘ALERT_MYUSER’,’’,0);

END;

Application tuning

Q: What is the OPTIMIZER_DYNAMIC_SAMPING setting default?

A: To enhance Query Optimization, the OPTIMIZER_DYNAMIC_SAMPING is set to


2 by default.

Q: How do you disable the Automatic PGA Memory Management?

A: In order to disable the Automatic PGA Memory Management set the parameter to 0.

Q: How do you gather statistics on dictionary tables in the Oracle 10g Database?

A: In Oracle Database 10g, you can gather statistics on dictionary tables (both fixed and
real) to get the best performance. You use the DBMS_STATS
.GATHER_DATABASE_STATS procedure with GATHER_SYS argument set to TRUE
or DBMS_STATS.GATHER_DICTIONARY_STATS. To use this, you should have the
ANALYZE ANY DICTIONARY system privilege. For example:

SQL> BEGIN

DBMS_STATS .GATHER_DATABASE_STATS(options=’GATHER AUTO’);

END;

/ -- Note: you should use GATHER only if you are using release 8i

Q: What is the Automatic Tuning Optimizer (ATO)?

A: It is a SQL automatic tuning optimaizer. When the optimizer is tuning a SQL


statement using ATO, it is called Automatic SQL Tuning.
Q: How do you perform automatic SQL tuning?

A:

Create a binding variable and then move your query into it.

SQL> VARIABLE my_query VARCHAR2(1000)

SQL> BEGIN

:my_query := ‘SELECT ename FROM iself.emp WHERE empno = 100;’

END;

Q: How do you use the DBMS_SQLTUNE package to create a tuning task by calling
the CREATE_TUNING_TASK function?

A: We use the DBMS_SQLTUNE package to create a tuning task by calling the


CREATE_TUNING_TASK function. This procedure creates an advisor task and sets its
corresponding parameters according to the user-provided input arguments. To execute
this you need one more binding variable to keep your task name.

SQL> VARIABLE my_task VARCHAR2(100)

SQL> BEGIN

:my_task := DBMS_SQLTUNE .create_tuning_task (

SQL_TEXT => :my_query,

BIND_LIST => SQL_BINDS(anydata.ConvertNumber(100)),

USER_NAME => ‘ISELF’,

SCOPE => ‘COMPREHENSIVE’,

TIME_LIMIT => 60,

TASK_NAME => ‘my_tuning_task’,


DESCRIPTION => ‘Query on EMP table …’);

END;

Q: How do you use the EXECUTE_TUNING_TASK procedure to start the tuning


process?

A: You need to invoke the EXECUTE_TUNING_TASK procedure to start the tuning


process.

SQL> BEGIN

DBMS_SQLTUNE .execute_tuning_task (TASK_NAME=>:my_task);

END;

Q: How do you call the REPORT_TUNING_TASK function to visualize the tuning


results?

A: The following is an example of how to call the REPORT_TUNING_TASK function


to visualize the tuning results.

SQL> SQL> SELECT DBMS_SQLTUNE .report_tuning_task

(TASK_NAME=>:my_task)

FROM dual;

Q: How do you store a SQL profile in the data dictionary?

A: When the SQL Tuning Advisor recommends a SQL Profile, then create the SQL
Profile by calling the ACCEPT_SQL_PROFILE function, which stores it in the data
dictionary. You should have the CREATE ANY SQL PROFILE privilege.

SQL> VARIABLE my_profile VARCHAR2(1000)

SQL> BEGIN
:my_profile := DBMS_SQLTUNE .accept_sql_profile

(TASK_NAME => ’my_tuning_task’);

END;

SQL> SELECT :my_profile FROM dual;

Database Resource Manager

Q: How to do you use the DBMS_RESOURCE_MANAGER package to tell the PMON


process to kill sessions that are idle for longer than 600 seconds and kill sessions that are
idle for more than 300 seconds and are blocking other sessions. We assumed that you
have already defined your plan as ‘MY_DAY_PLAN’ and your group as
‘MY_FIRST_GROUP.’

A:

SQL> BEGIN

DBMS_RESOURCE_MANAGER .create_plan_directive (

PLAN => ‘MY_DAY_PLAN’,

GROUP_OR_SUBPLAN => ‘MY_FIRST_GROUP’,

COMMET => ‘Limit user idle time’,

MAX_IDLE_TIME => 600,

MAX_IDLE_BLOCKER_TIME => 300);

END;

/
Scheduler

Q: What is the DBMS_SCHEDULER package?

A: Oracle Database 10g provides scheduling capabilities through the database Scheduler
. It uses the DBMS_SCHEDULER package. The Scheduler offers far more functionality
than the DBMS_JOB package. You can create a job class a job class always belongs to
the SYS schema. Since the priority of jobs change over a period, now you can also create
a window. For example: you can create a window for the month of October that uses the
END_OF_YEAR plan and is active every day from 8:00 a.m. to 6:00 p.m. Eastern
standard Time (EST).

Q: How do you monitor a Job using the Database Control page?

A: Log in to EM Database Control as the ISELF user. From the Database Control home
page click on the Administration tab. In the ‘Scheduler ’ region, click the ‘Jobs’ link.

You should see:

One schedule, called DAILY_PURGE_SCHEDULE by clicking the Schedulers link,

Two windows, called WEEKNIGHT_WINDOW and WEEKEND_WINDOW by


clicking the Windows link, and

Two job classes, called DEFUALT_JOB_CLASS , AUTO_TASKS_JOB_CLASS by


clicking the Job Classes link.

Q: How do you add a Job using the Database Control page?

A: Click the Create button on the Scheduler Jobs page; fill out the applicable fields;

Back to the Create Job page; enter location of your job script in the Executable Name
field; and then click the Schedule tab.

On the Schedule page, make sure that the immediate radio button and the Repeat field are
set to Do Not Repeat.
Q: How to create a schedule named MY_SCHEDULE owned by ISELF that executes
every five seconds.

A:

SQL> CONNECT iself/schooling

SQL> BEGIN

DBMS_SCHEDULER .create_schedule (

SCHEDULE_NAME => ‘MY_SCHEDULE’,

START_DATE => SYSTIMESTAMP,

REPEAT_INTERVAL => ‘FREQ=SECONDLY;INERVAL=5’,

COMMENTS => ‘This is my first created schedule.’);

END;

Now, you should be able to see it in your Database Control page.

Q: How to schedule a job that calls your created online-backup every night at 10 p.m.?

A: You should have been granted CREATE JOB to be able to create a job. Jobs are
created as disabled by default. You must enable them explicitly.

SQL> BEGIN

DBMS_SCHEDULER .create_job (

JOB_NAME => ‘ISELF.ONLINE_BACKUP’,

JOB_TYPE => ‘EXECUTABLE’,

JOB_ACTION => ‘/home/my_Nightly_online_backup.sh’,

START_DATE => TRUNC(SYSDATE+1)+22/24,

REPEAT_INTERVAL => ‘TRUNC(SYSDATE+1)+22/24’,


COMMENTS => ‘My nightly online backup’);

END;

Q: Assuming that you have a procedure that collects information daily called
DAILY_DATA_GATHERING. Now, you should create a problem to call this procedure
and create a job to run it daily. How you do that?

A:

SQL> BEGIN

DBMS_SCHEDULER .create_program (

PROGRAM_NAME => ‘DAILY_GATHERING’,

PROGRAM_ACTION => ‘ISLEF.DAILY_DATA_GATHERING’,

PROGRAM_TYPE => ‘STORED_PROCEDURE’,

ENABLED => TRUE);

END;

SQL> BEGIN

DBMS_SCHEDULER .create_job (

JOB_NAME => ‘ISELF.DAILY_GATHERING_JOB’,

PROGRAM_NAME => ‘ISLEF.DAILY_GATHERING’,

START_DATE => TRUNC(SYSDATE+1)+22/24,

REPEAT_INTERVAL => ‘TRUNC(SYSDATE+1)+22/24’,

COMMENTS => ‘Daily Data Gathering Job.’);

END;

/
You could also use your created schedule:

SQL> BEGIN

DBMS_SCHEDULER .create_job (

JOB_NAME => ‘ISELF.DAILY_GATHERING_JOB’,

PROGRAM_NAME => ‘ISLEF.DAILY_GATHERING’,

SCHEDULE_NAME => ‘MY_SCHEDULE’);

END;

Tablespace Monitoring

Q: How an alert will raise or clear based on a tablespace size?

A: In the Oracle Database 10g, tablespace thresholds are defined in terms of a


percentage of the tablespace size. When the threshold crosses their limits, an appropriate
alert will raise or clear.

Q: When do you need to enable row movement on a segment?

A: Since a shrink operation may cause ROWIDs to change in heap-organized segment,


before executing a shrink operation you should enable row movement on a segment.

For example:

SQL> ALTER TABLE emp ENABLE ROW MOVEMENT ;

SQL> ALTER TABLE emp SHRINK SPACE CASCADE ;

Q: On the USERS tablespace, set a warning threshold of 80% and a critical threshold of
95%.
A:

SQL> BEGIN

DBMS_SERVER_ALERT .set_threshold (

DBMS_SERVER_ALERT .tablespace_pct_full,

DBMS_SERVER_ALERT .operator_ge, 80,

DBMS_SERVER_ALERT .operator_ge, 95, 1, 1, NULL,

DBMS_SERVER_ALERT .object_type_tablespace, ‘USERS’);

END;

You can use the NULL value to return to the database-wide default values.

Q: How do you check the database-wide threshold values for the USERS tablespace?

A:

SQL> SELECT warning_value, critical_value

FROM dba_thresholds

WHERE metrics_name = ‘Tablespace Space Usage’ AND

object_name = ‘USERS’

Q: How do you turn off the space-usage tracking for the USER tablespace?

A:

SQL> BEGIN

DBMS_SERVER_ALERT .set_threshold (

DBMS_SERVER_ALERT .tablespace_pct_full,
DBMS_SERVER_ALERT .operator_do_not_check, ‘0’,

DBMS_SERVER_ALERT .operator_do_not_check, ‘0’, 1, 1, NULL,

DBMS_SERVER_ALERT .object_type_tablespace, ‘USERS’);

END;

Q: How do you reset the database-wide threshold values of the USERS tablespace to the
default database values?

A:

SQL> BEGIN

DBMS_SERVER_ALERT .set_threshold (

DBMS_SERVER_ALERT .tablespace_pct_full,

NULL, NULL, NULL, NULL, 1, 1, NULL,

DBMS_SERVER_ALERT .object_type_tablespace, ‘USERS’);

END;

Q: How do you check the status of your threshold?

A:

SQL> SELECT reason, resolution

FROM dba_alert_history

WHERE object_name = ‘USERS’;

SQL> SELECT reason, message_level

FROM dba_outstanding_alerts

WHERE object_name = ‘USERS’;


Big and small file tablespaces

Q: What is a BIGFILE tablespace?

A: It is the Oracle Database 10g feature. A bigfile tablespace (BFT ) is a tablespace


containing a single file that can have a very large size and on the other hand a smallfile
tablespace can contain many data files. The size of a bigfile can reach to 128TB
depending on the Oracle block size. An Oracle database can contain both bigfile and
smallfile tablespaces. You can change the default tablespace type to BIGFILE or
SMALLFILE.

Q: How do you set the default tablespace type to BIGFILE ?

A: To set the default tablespace type to BIGFILE , you can use either CREATE
DATABASE or ALTER DATABASE.

Q: how do you display the default tablespace type?

A: You use the DATABASE_PROPERTIES dictionary view to display the default


tablespace type for the database:

SQL> SELECT property_value FROM database_properties

WHERE property_name = ‘DEFAULT_TBS_TYPE’;

Q: Use the DBA_TABLESPACES dictionary view to display whether all tablespace is


bigfile (YES) or smallfile (NO).

A:

SQL> SELECT tablespace_name, bigfile FROM dba_tablespaces;


Q: Use the V$TABLESPACE dynamic view to display whether all tablespace is bigfile
(YES) or smallfile (NO).

A:

SQL> SELECT name, bigfile FROM v$tablespace;

Q: What are the difference between a BIGFILE rowid and a small file rowid?

A: Extended ROWID format :

For Smallfile tablespaces is Object# - File# - Block# - Row#

For Bigfile tablespaces is Object# - Block# - Row#

Q: Create a temporary tablespace group that it consists of only temporary tablespaces.

A:

SQL> CREATE TEMPORARY TABLESPACE mytemp1

TEMPFILE ‘temp_01.dbf’ SIZE 500M

TABLESPACE GROUP mygroup;

The mygroup group has one more temporary tablespace in its groups. If you do not want
to assign any temporary tablespace to a group do the following:

SQL> CREATE TEMPORARY TABLESPACE mytemp2

TEMPFILE ‘temp_02.dbf’ SIZE 500M

TABLESPACE GROUP ‘’;

Q: Use the DBA_TABLESPACE_GROUPS view to display all tablespace associated


to their groups.

A:

SQL> SELECT tablespace, group_name FROM dba_tablespace_groups;


Q: Create a tablespace with a BIGFILE default tablespace type.

A:

SQL> CREATE BIGFILE UNDO TABLEPSACE my_big_tbs

DATAFILE ‘/u01/oradatta/tbs_01.dbf’ SIZE 1G;

Q: Can you add more datafiles?

A: If you try to add more datafile to above tablespace, do the following.

SQL> ALTER TABLESPACE my_big_tbs

ADD DATAFILE ‘/u02/oradata/tbs_02.dbf’ SIZE 100k;

Notice, since a bigfile tablespace can contain only one data file, your command should
fail.

Q: How do you get a BIGFILE ROWID?

A: To get its ROWID, you should use the following database package
(DBMS_ROWID).

SQL> SELECT distinct DBMS_ROWID.ROWID_RELATIVE_FNO


(ROWID,’BIGFILE ’)

FROM test_rowid;

General Storage Enhancements


Q: What is System Auxiliary Tablespace in the Oracle 10g Database?

A: The Oracle 10g database added one more tablespace (SYSAUX) to help the
SYSTEM tablespace. The SYSAUX tablespace is an auxiliary tablespace to the
SYSTEM tablespace. It is a mandatory tablespace and should be created at database
creation time. You cannot drop or rename this tablespace.

Q: What does the SYSAUX tablespace hold?

A:

Text, Ultra Search


*

Intermedia, Spatial
*

Scheduler
*

OLAP
*

XML DB
*

Workspace Manager
*

Data Mining
*

Server Manageability Components


*

Recovery Catalog
*

EM Repository
*

Analytical Workspace Object table


*

LogMinor, Log Standby, Streems


*

Statspack

Q: How can you monitor the space usage of each occupant inside the SYSAUX
tablespace ?

A: Use the following SQL statement.

SQL> SELECT occupant_name, space_usage_kbytes

FROM v$sysaux_occupants

Q: What are the Mandatory attributes of SYSAUX?

A:

PERMANENT
*

READ WRITE
*

EXTENT MANAGEMENT LOCAL


*

SEGMENT SPACE MANAGEMENT AUTO

Q: What are its benefits?

A: It reduces the number of tablespaces to manage. You don’t need to create the
TOOLS, OEM_REPOSITROY, DRSYS, CWMLITE, ODM, etc tablespaces.
You reduce the load on the SYSTEM tablespace.

Q: Can you rename SYSTEM or SYSAUX tablespaces?

A: Now you can rename tablespace in the Oracle 10g database. You can not rename the
SYSTEM and SYSAUX tablespaces. You can rename any permanent or temporary
tablespaces. All tablespaces must have their datafiles online. Your database spfile will be
updated.

Q: How do you rename a tablespace?

A: To rename a tablespace do the following SQL statement.

SQL> ALTER TABLESPACE tools RENAME TO my_tools;

Q: Can you change the default Permanent Tablespace in the Oracle 10g database?

A: Now, you can change the default permanent tablespace for non-system users.

Q: How can you check what your default permanent tablespace is?

A: Query the following SQL statement.

SQL> SELECT property_value

FROM database_properties

WHERE property_name =

‘DEFAULT_PERMANENT_TABLESPACE’

Q: Change your default tablespace to USERS.

A: Assuming your default tablespace is SYSTEM, and then you change it to USERS.
SQL> ALTER DATABASE DEFAULT TABLESPACE users;

Q: How can you copy files without using system operating system commands?

A: You can use the COPY_FILE procedure in the DBMS_FILE_TRANSFER package


to copy a file from one place to another. You should make sure to create source and
destination directories and you have a read access on the source directory and a write
access on the destination directory.

Assuming we are going to copy file a1.dbf from location /u01/oradata/school to


location /u02/oradata/school.

SQL> CREATE DIRECTORY my_source AS ‘/u01/oradata/school’;

SQL> CREATE DIRECTORY my_destination AS ‘/u02/oradata/school’;

SQL> BEGIN

DBMS_FILE_TRANSFER .COPY_FILE (

SOURCE_DIRECTORY_OBJECT => ‘MY_SOURCE’,

SOURCE_FILE_NAME => ‘a1.dbf’,

DESTINATION_DIRECTORY_OBJECT => ‘MY_DESTINATION’,

DESTINATION _FILE_NAME => ‘a1.dbf’);

END;

Q: What does the Redo Logfile size advisor in the Oracle 10g database?

A: It determines the optional smallest online redo log file size based on the current
FAST_START_MTTR_TARGET setting and the corresponding statistics. To enable the
Redo Logfile Size Advisor , you should set the FAST_START_MTTR_TARGET
parameter. Note that an online redo log file size is considered optimal if it does not drive
incremental check pointing more aggressively than needed by
FAST_START_MTTR_TARGET.

Q: Make the retention period for one day with an interval off “0” which switches off
snapshot collection.

A:

SQ> EXEC dbms_workload_repository .modify_snapshot_settings (1440, 0); -- 1440


minute or 1 day and “0” switches OFF snapshot collection.

Automatic Storage Management (ASM )

Q: What does ASM provide?

A: ASM provides a vertical integration of the file system and the volume manager that
is specifically built for Oracle database files.

Q: What are its key features and benefits?

A:

Stripes files rather than logical volumes


*

Online disk reconfiguration and dynamic rebalancing


*

Adjustable rebalancing speed


*

Provides redundancy on a file basis


*
Supports only Oracle database files
*

Custer-aware
*

Automatically installed

Q: Does ASM have a data dictionary?

A: ASM instance does not have a data dictionary and it is restricted to few SQL
commands and Dynamic Performance view.

Q: How do you create a disk group by using ASM ?

A: The following are examples of creating and deleting disk groups.

Creating a diskgroup:

SQL> CREATE DISKGROUP dgora1 NORMAL REDUNDANCY

FAILGROUP controller1 DISK

‘/dev/rdsk/c0t0d0s2’ NAME mydisk SIZE 200G FORCE,

‘/dev/rdsk/c0t1d0s2’,

‘/dev/rdsk/c0t2d0s2’

FAILGROUP controller2 DISK

‘/dev/rdsk/c1t0d0s2’,

‘/dev/rdsk/c1t1d0s2’,

‘/dev/rdsk/c1t2d0s2’;

Q: How do you delete a disk group by using ASM ?

A: Dropping a diskgroup:
SQL> DROP DISKGROUP dgora1 INCLUDING CONTENTS;

Q: How do you add a disk to an existing disk group?

A: The following are examples of how to add disks to an existing disk group.

SQL> ALTER DISKGROUP dgora1

ADD FAILGROUP controller1

‘/dev/rdsk/c0t3d0s2’ NAME a5;

Q: How do you remove a disk to an existing disk group?

A: To remove a disk:

SQL> ALTER DISKGROUP dgora1 DROP DISK a5;

Q: Can you undo the removed disk? How?

A: Yes. To undo the removed disk do the following SQL statement. This only works if
the status of drop is pending or the drop function was not completed yet.

SQL> ALTER DISKGROUP dgora1 UNDROP DISKS;

Q: How do you display a list of your diskgroups?

A: To display a list of diskgroups.

SQL> SELECT name FROM v$asm_diskgroup;

Q: How do you display a list of associated ASM disks?

A: To display a list of associated ASM disks.


SQL> COL name FORMAT a20

SQL> COL failgroup FORMAT a20

SQL> SELECT name, failgroup, bytes_read, bytes_written

FROM v$asm_disk

Q: How do you display a list of associated ASM files?

A: To display a list of associated ASM files.

SQL> SELECT group_number, file_number, bytes, type, striped

FROM v$asm_file

Q: How do you create a tablespace that uses an ASM disk group?

A: To create a tablespace that is stored in the ASM disk group dgora1.

SQL> CREATE TABLESPACE mytablespace2

DATAFILE ‘+dgora1’ SIZE 100m

Q: How do you add one addition disk to your system?

A: Do the following.

SQL> HOST dd if=/dev/zero of=/u02/oradata/school/diska abs=1024k count=200

SQL> SELECT name, failgroup, bytes_read, bytes_written

FROM v$asm_disk
/

SQL> ALTER DISKGROUP dgora1

ADD DISK ‘/u02/oradata/school/diska’

Execute the following query until you get ‘no rows selected.’

SQL> SELECT operation, est_minutes

FROM v$asm_operation

Again, display a list of associated ASM disks.

SQL> SELECT name, failgroup, bytes_read, bytes_written

FROM v$asm_disk

Now, you should see one more disk was added to disk group.

Security VPD

Q: What is VPD in the Oracle 10g Database?

A: In the Oracle 10g database, there is a feature called Virtual Private Database (VPD ).
It enables you to build applications that enforce your security policy. When a user
requests a query, the server dynamically modifies the user’s SQL statement, which is not
transparent to the user. The modification is based on a WHERE clause returned by a
function.
The Oracle 10g database more features that are important to note

Q: How do you use the V$FAST_START_TRANSACTIONS view to monitor (in real-


time) normal transaction rollback and transaction recovery by SMON?

A:

SQL> SELECT * FROM v$fast_start_ transactions;

Q: How do you use the V$FAST_START_SERVERS view to display historical


information about transaction recovery?

SQL> SELECT * FROM v$fast_start_servers;

Q: How do you use the DBA_ENABLED_TRACES view to display enabled and


disabled trace?

A:

SQL> SELECT * FROM dba_enabled_traces;

Q: What is case-insensitive sorting in the Oracle 10g?

A: In the Oracle 10g database, you can use the ALTER SESSION command to change
NLS_SORT for your session to use case-insensitive binary sorting.

Q: What is Quote Operator q?

A: Now, you can eliminate previous additional quotation string. See the following
example:

SQL> UPDATE customers

SET comments =
q’X In this example, ‘X’ is used as the quotation mark delimiter. X’;

WHERE ID = 100;

SQL> COMMIT;

Q: What does the UTL_MAIL package?

A: You can send e-mail to a user. In order to use the package, you should have already
run the utlmail.sql and prvtmail.plb scripts located in the
$ORACLE_HOME/rdbms/admin directory.

Oracle Grid

Q: What is the Oracle 10g Database Grid?

A: Yesterday was Internet and today is Grid. It looks like the technology finds its way to
hang on something to grow. Now, there is a committee called the Global Grid Forum
(GGF) that is developing standards for Grid computing.

Q: List some of the most important features of the Oracle 10g Grid.

A: The following are some of the most important features that enable Grid computing at
the Oracle 10g Database level:

Automatic Storage Management


*

Portable Clusterware
*
High-Speed InfiniBand Network Support
*

Real Application Clusters and automatic workload management


*

Resource Manager
*

Oracle Streams
*

Centralized Management with Enterprise Manager Grid Control


*

Oracle Database 10g New self-management feature


*

Q: What is OEM 10g?

A: It is Oracle Enterprise Manager with features that are more new. It can automatically
alert you to new critical patches. You can use the patch wizard to select an interim patch
and see if any of your system requires it. It is integrated with a build-in MetaLink
connection.

Q: How do you stop the Oracle Management Server?

A:

# emctl stop oms

Q: How do you start the Oracle Management Server?

A:

# emctl start oms


Q: How do you get the status of the Oracle Management Server?

A: Do the following command:

# emctl status oms

Q: How do you start EM Database Control ?

A:

# emctl start dbconsole

Q: How do you stop the EM Database Control ?

A:

# emctl stop dbconsole

Q: How do you get the status of the EM Database Control ?

A:

# emctl status dbconsole

Q: What is the default port for your Web Browser?

A: The default port is 5500 and you can access it by opening your Web browser and
enter the following URL: http://myserver:5500/em

Navigate the Oracle EM Grid Control


Q: How do you create an Oracle user by using the EM Database Control ?

A: Go to the EM Database Control home page as sysdba and click on Administration >
Users. On the Users page click on the Create button. You should specify the Name, Enter
Password, Confirm Password, Default Tablespace, and Temporary Tablespace fields.
Then click on the Roles tab and click on the Modify button; select Resource and DBA
from the Available Roles list. Once done, click the Move link and click the OK button.
When you are returned to the Create User page, click the OK button.

Q: How do you export tables from a schema by using the EM Database Control ?

A: Go to the EM Database Control home page as sysdba. Click on the Administration


tab; click on the Tables link in the Schema region; select your schema in the Schema field
in the Search region; and click the Go button. Select your exported tables from the
Results region; Select Show Dependencies from the Actions drop-down list; and then
click on the Go button in the Results region. On the Export:Review page, click on the
Submit Job button.

Q: How do you import tables from a schema by using the EM Database Control ?

A: Go to the EM Database Control home page as sysdba. Click on the Maintenance


link; click on the Import from Files link; make sure that the Database Version of Files to
Import field is set to 10g or later; and click the Go button. In the Files region, select your
directory from where the Data Pump Import job can retrieve your exported Dump File
Set; in the Import Type region, select the Tables option button and make sure the host
credentials are correct; then click on the Continue button. Click on the Add button and in
the Import:Add Tables page, enter your schema in the Schema field in the Search region;
then click on the Go button. Select your tables; click on the Select button and On the
Import:Re-Mapping page, click the Add Another Row button in the Re-Map Schema
region. Then click the Next button. On the Import:Review page, click on the Submit Job
button; on the Status page, click the View Job button; refresh your browser page until the
Status field reads Succeeded; and then click the Import link to look at the log file.

Q: How do you retrieve the latest ADDM and determine the cause of the problem by
using the EM Database Control ?

A: Go to the EM Database Control home page as sysdba and click on the Advisor
Central link on the Related Links section; select ADDM in the Advisory Type drop-
down list; select Last 24 Hours in the Advisor Runs drop-down list; and when it is done,
click on the Go button. Then select the latest ADDM task completed by the ADDM user;
click the View Result button; it brings you to the ADDM page and you can see the results
for the Performance Analysis; To investigate further, click on the SQL Statements
Consuming Significant Database Time Were Found link; it will brings you to the
Performance Finding Details page. To tune the statement, click on the Run Advisor Now
button; when the analysis finished, you will be directed to the Recommendations for SQL
ID: … page.

Q: How do you shutdown and startup your databases using an initialization parameter
file by using the EM Database Control ?

A: Go to the EM Database Control home page as sysdba; click the Shutdown button;
you should specify host and target database credential; save them and click on the OK
button. On the Startup/Shutdown: Confirmation page click the Yes button; on your
database page, click the Startup button. Click on the Advanced Options button; make sure
that you select your initialization parameter file with its location and then click the OK
button.

Q: How do you check or resize the size of the various SGA buffers using the EM
Database Control and how to enable the Automatic Shared Memory Management by
using the EM Database Control?

A: Go to the EM Database Control home page as sysdba; click on the Administration


tab; click on the Memory Parameters link in the Instance region; and now you should see
the status Automatic Shared Memory Management (disable or enable), Shared Pool size,
Buffer Cache, Large Pool, Java Pool, Total SGA, Maximum SGA size, etc. If the
Automatic Shared Memory Management was disabled on the Memory Parameters page,
click on the Enable button to enable it.

Q: How do you look at the corresponding metrics graphic rate by using the EM
Database Control ?

A: Go to the EM Database Control home page as sysdba; click on the All Metrics link;
expand the Throughput link; under this link, click on the User Commits (per second) link;
make sure that the View Data field is set to very short period of time (ex: Real Time: 10
Seconds Refresh). Now here, depending on your workload, you should be able to see
your graph.
Q: How do you find a high load SQL statement and fix it by looking at an ADDM
report analysis during the problem by using the EM Database Control ?

A: Go to the EM Database Control home page as sysdba.

If the time corresponding to the problem corresponds with the latest ADDM , then you
should find the link corresponding to the correct performance analysis directly in the
Diagnostic Summary region of the EM Database Control home page. If not, then go to
the Advisor Central page and search for the correct ADDM task. To fix your problem,
click the finding with the highest impact on the database time on the corresponding
ADDM page. It should correspond to a SQL Tuning recommendation. On the
Performance Finding Details page, you see the high-load SQL statement; click on the
Run Advisor Now button for the highest high-load SQL statement detected. Once was
done, you get the details of the corresponding recommendations. You can also click on
the Original Explain Plan button to see the original plan. If you have a proposed SQL
command, click on the Implement button after selecting the appropriate SQL command
from the Recommendations table.

Q: How do you determine the most important wait category from the Sessions: Waiting
and Working graph by using the EM Database Control ?

A: Go to the EM Database Control home page as sysdba; click on the Performance tab;
if the period for which you want to observe your database is on the Sessions: Waiting and
Working graph use the current graph. If the period is no there, select the Historical value
from the View Data drop-down list. On the Performance page click on the User I/O
category in the graph’s legend. Select the top SQL statement and you should see the SQL
Details page. Click on the Execution History tab to see what isgoing on to the statement.
Shorten the Seconds Per Execution option button to get a better understanding of the
graph.

Q: How do you use the SQL Access Advisor to generate recommendations for a SQL
tuning set by using the EM Database Control ?

A: Go to the Database Control home page as sysdba; click on the Advisor Central link;
click on the SQL Access Advisor link; then select the Import Workload from SQL
Repository option button; set the SQL Tuning Set field to your SQL tuning set; and click
the Next button. On this page, click on the Both Indexes and Materialized Views and
Comprehensive Mode buttons; click on the Show Advanced Options link and make sure
your options are set and then click the Next button. On the SQL Access Advisor:
Schedule page, select Standard in the Schedule Type file; on the Review page, click the
Submit button. Refresh the page until you get the COMPLETED status. Now, select your
SQL Access Advisor task and click the View Result button.
Q: How do you create a job and schedule it to run by using the EM Database Control ?

A: Go to the Database Control home page as sysdba; click on the Administration tab; in
the Scheduler section, click on the Jobs link; on this page, click on the Create button; on
the page, enter a job name the Name field; make sure the set the Logging Level (RUNS),
Job Class (DEFAULT_JOB_CLASS), Auto Drop (FALSE), and the Restartable
(FALSE). In the Command section, click the Change Command Type button; on the
Select Command Option, select the In-line Program: Executable radio button; and the
click the OK button. On the Create Job page, enter your shell executable job in the
Executable Name field and click the Schedule tab. On this page, select your schedule
option and click OK.

Q: How do you verify that your schedule was created by using the EM Database Control
?

A: Go to the Database Control home page as sysdba; click on the Administration tab;
click the Schedules link on the Scheduler region.

Q: How do you change the Tablespace Space Usage thresholds of a tablespace by using
the EM Database Control ?

A: Go to the Database Control home page as sysdba; click on the Administration tab;
click on the Tablespaces link; select your tablespace; select Edit > Thresholds; select
Specify Thresholds, by percent used; now specify the Warning(%) and Critical (%)
fields; and then click the Apply button.

Q: How do you run the Segment Advisor for a tablespace by using the EM Database
Control ?

A: Go to the Database Control home page as sysdba; click on the Administration tab;
click on the Tablespace link; select your tablespace; select Run Segment Advisor from
the Action field; click the Go button; check that the Comprehensive mode is selected;
click the Continue button; check all the options on the Segment Advisor: Schedule, and
Options pages. On the Review page, click the Submit button and click refresh until you
see COMPLETED. Select your task and click the View Result button to go to the
Segment Advisor Recommendations page. Accept all recommendation and then click the
Schedule Implementation button.
Q: How do you use the Undo Advisor to get recommendations to size your UNDO
tablespace by using the EM Database Control ?

A: Go to the Database Control home page as sysdba; click on the Administration tab;
click on the UNDO Management link; on this page change the Analysis Time Period
field to Last One Hour and click the Update Analysis button; on the UNDO Management
page, you should see Oracle 10g recommendation; click the UNDO Advisor button to
get more info. You can look at the Required Tablespace Size by Undo Retention Length
graph. If you change the New Undo Retention field for example you will see the impact
on your undo tablespace size. On the UNDO Management page, click the Edit Undo
Tablespace button. Change the size or add datafile and click the Continue button. After
you are back to the Edit Tablespace page click the Apply button.

Q: How do you change the size of flash recovery area by using the EM Database
Control ?

A: Go to the Database Control home page as sysdba; click on the Maintenance tab; click
on the Configure Recovery Settings link; in the Flash Recovery Area Size field, you can
enter a value that you want to change and then click on the Apply button.

Q: How do you backup your whole database to tape by using the EM Database
Control ?

A: Go to the Database Control home page as sysdba; click on the Maintenance tab; click
on the Schedule backup link; select Customized from the Backup Strategy drop-down
list; select Whole Database; make sure that you enter your host credentials and click the
Next button; on the Options page, click NEXT; on the Setting page, select Tape, then
NEXT; on the Schedule page, click NEXT; on the Review page, click Submit Job. Now
you should be able to view your job by clicking on the View Job button. Once the job is
done, click the Backup link on the Execution page. You see what you want to see.

Q: How do you use the flashback feature to recover a dropped table by using the EM
Database Control ?

A: Let assume that still your table is in the Recycle Bin area. Go to the Recycle Bin
page; select your object; and click the Flashback Drop button. You will be prompted to
the Perform Recovery: Rename page to change the original name if you wish. Leave the
original name, and click NEXT. On the Review page, click the Submit button and click
OK on the Confirmation page. Now you should see the Recycle Bin page and your object
should have been disappeared.

Q: How do you determine the Redo Log File size using the Sizing Advice by using the
EM Database Control ?

A: Go to the Database Control home page as sysdba; click on the Administration tab;
click on the Redo Log Groups link; on this page you can see the redo log group size;
select Sizing Advice in the Actions drop-down list and click the Go button. Now, you
should see the recommended optimal redo log file size in the Update Message region of
the Redo Log Groups page.

Oracle DBA #1 Fundamental Exam


Answers
NOTE: The answers go with their sequences. If a question was not answer, that means
that it a repeating question and the answer was given by the previous questions or it is not
in the scope of this subject.

“If you would lift me up you must be on higher ground.”

--Ralph Waldo Emerson


Answers:
Q: What are the Oracle Architectural components?
A: The Oracle Architectural components are:
• Memory (SGA) such as Buffer Cache, Shared Pool, Redo Log Buffer, Large Pool,
Java Pool, etc.
• Background Processes such as Log Writer, DB Writer, Checkpoint, Archiver,
SMON, etc.
• Oracle Physical Layout such as Datafiles, Controlfiles, Online Redo log files,
Parameter file, Password file, etc.

Q: What are the Oracle Memory Components?


A: All components such as Shared Pool (Library Cache, Dictionary Cache), Buffer
Cache, Online Redo Log file, Large Pool, Java Pool as well as a few other items are
referred to as the System Global Area (SGA). And the place stores information like bind
variable values, sort areas, cursor handling, etc for a specific user is called Program
Global Area (PGA). The PGA is used to store only real values in place of bind variables
for executing SQL statements. The combination of these two memories structure while
they are running is called Oracle Instance.

Q: What is the Server Parameter File?


A: The Server Parameter File is a binary file and Oracle uses it to change the most of its
system parameters dynamically.

Q: What is the Parameter File?


A: The Parameter file is a configuration file and it contains all the Oracle instance and
database configuration parameters. When you change any parameter using this file, you
should shutdown and startup the Oracle Database.

Q: How do you use the init.ora file?


A: The init.ora file is called initialized or parameter file. It is a configuration file.

Q: What is the System Global Area (SGA)?


A: The SGA contains of Shared Pool (Library Cache, Dictionary Cache), Buffer Cache,
Online Redo Log file, Large Pool, Java Pool as well as a few other items.

Q: What is the Shared Pool in SGA?


A: The Shared Pool contains the Library Cache and the Dictionary Cache as well as a
few other items, which are not in the scope of this section. The Library Cache holds all
users’ SQL statements, Functions, Procedures, and Packages. It stores parsed SQL
statement with its execution plan for reuse. The Dictionary Cache, sometimes also
referred to as the Row Cache, holds the Oracle repository data information such as tables,
indexes, and columns definitions, usernames, passwords, synonyms, views, procedures,
functions, packages, and privileges information.

Q: What does the Buffer Cache hold in SGA?


A: The Buffer Cache holds users’ data. Users query their data while they are in the
Buffer Cache. If user’s request is not in the Buffer Cache then server process has to bring
it from disk. The smallest unit in the buffer cache is an Oracle block. The buffer cache
can be increased or decreased by granule unit. The smallest Granule Unit is 4Meg if the
SGA size is less than 128Meg and the smallest Granule Unit become 16Meg is the SGA
size is more than 128Meg.

Q: What are the differences between the Library Cache and Dictionary Cache?
A: The Library Cache holds user’s SQL statements, PL/SQL programs, but the
Dictionary Cache holds only repository information such as user’s table name, its access
privileges, and etc.

Q: What is the Redo Log Buffer in SGA?


A: The Redo Log Buffer holds users’ entries such as INSERT, UPDATE, DELETE, etc
(DML) and CREATE TABLE, DROP TABLE (DDL). The Redo Entries are information
that will be used to reconstruct, or redo, changes made to a database. The Log
Writer writes the entries into the Online Redo Log files when a COMMIT occurs, every 3
seconds, or when one third of the Redo Log Buffer is full. That will guarantee a database
recovery to a point of failure if an Oracle database failure occurred.

Q: Describe the Large Pool component in SGA.


A: The Large Pool holds information about the Recovery Manager (RMAN) utility
when RMAN is running. If you use the Multi-threaded Server (MTS) process, you may
allocate the Oracle Memory structure such that you can get advantage of using Large
Pool instead of the Shared Pool. Notice that when you use dedicated servers, user session
information is housed in the PGA.

Q: Describe the Multi-threaded Server process.


A: The Multi-threaded Server process will be used when a user send his/her request by
using a shared server. A user’s request will be assigned to a dispatcher based on the
availability of dispatchers. Then the dispatcher will send or receive request from an
assigned shared server.

Q: What are PGA and UGA?


A: When you are running dedicated servers then the session information can be stored
inside the process global area (PGA). The UGA is the user global area, which holds
session-based information. When you are running shared servers then the session
information can be stored inside the user global area (UGA).

Q: Describe the log writer background process (LGWR).


A: The LGWR’s job is to write the redo user’s entries from the Redo Log Buffer.

Q: How often does LGWR write user’s entries to the Online Redo Log Buffer files?
A: It writes user’s entries when the buffer exceeds one third of the Redo Log Buffer,
every 3 seconds, or when a user executes the commit SQL statement.

Q: Describe the Checkpoint process.


A: The Checkpoint signals DB writers to write all dirty blocks into the disk. The
Checkpoint will occurred either by a specific defined time, size of the Online Redo Log
file used by DBA, or when an Online Redo log file will be switched from on log file to
another.

Q: How do you automatically force the Oracle to perform a checkpoint?


A: The following are the parameters that will be used by a DBA to adjust time or
interval of how frequently its checkpoint should occur on its database.
LOG_CHECKPOINT_TIMEOUT = 3600 # every one hour
LOG_CHECKPOINT_INTERVAL=1000 # number of OS blocks

Q: What is the Recovery Process?


A: The RECO will be used only if you have a distributed database. You use this process
to recover a database if a failure occurs due to physical server problem or communication
problem.

Q: What is the Lock Background Process?


A: The LCKn background process will be used if you have multiple instances accessing
to only one database. An example of that is a Parallel Server or a Real Application
Clusters.

Q: How does the Archive Process work?


A: This background process archives the Online Redo Log file when you are manually
or automatically switching an Online Redo Log file. An example of manually switching
is: ALTER SYSTEM SWITCH LOGFILE or ALTER SYSTEM ARCHIVE LOG
CURRENT.

Q: How do you configure your database to do an automatic archiving?


A: SQL> ALTER SYSTEM ARCHIVE LOG CURRENT;

Q: What is the System Monitor Process?


A: The SMON job is: when you start your database, it will make sure that all datafiles,
controlfiles, and log files are synchronized before opening a database. If they are no, it
will perform an instance recovery. It will check the last SCN that was performed against
the datafiles. If it finds that there are transactions that were not applied against the
datafile, then it will recover or synchronize the datafile from either the Online Redo Log
files or the Archive Log files. The smaller Online Redo log files will bring a faster
database recovery.

Q: Describe the Program Monitor Process Job.


A: A user may be disconnected either by canceling its session or by communication
link. In either act, the PMON will start and perform an action to clean the reminding
memory allocation that was assigned to the user.

Q: What are the differences between the SPFILE and PFILE startup?
A: You can read or change the init.ora file (PFILE) for startup of the Oracle database. It
contains all Oracle parameters file to configure a database instance. In this file, you can
reset and change the Buffer Cache size, Shared Pool size, Redo Log Buffer size, etc. You
also can change the location of your control files, mode of a database such as archivelog
mode or noarchivelog mode, and many other parameter options that you will learn them
in the course of this book.
But using Server Parameter File-SPFILE, you can not read the file. It is in a binary
format. If you want to change database parameters dynamically, you should create the
Server Parameter file (CREATE SPFILE FROM PFILE) and startup your database using
the SPFILE file. There are some few parameters that you still need to shutdown and
startup the database, if you want to make the parameter in effect.

Q: What is the controlfile?


A: You cannot read this file and it is in a binary format. If you want to see the content of
control file or the layout of your database, you should use the ALTER DATABASE
BACKUP CONTROLFILE TO TRACE statement. It writes a trace file into the
%ORACLE_BASE\admin\<db-name>\UDUMP directory.

Q: How do you backup your database controlfiles?


A: SQL> ALTER DATABASE BACKUP CONTROLFILE TO c:\ctnlrfl.bk;

Q: What does a controlfile contain?


A: It contains information the structure of your database layout, database name, last
System Change Number (SCN) number, your database mode (archivelog mode or
noarchivelog mode), maximum number of log files, maximum number of log members,
maximum number of instances, maximum of number of datafiles, the location of the
database Online Redo Log files, and backup information.

Q: Describe the password file.


A: The password file is an external file that contains the password of sysdba or sysoper.
To use the password file you should set the REMOTE_LOGIN_PASSWORD parameter
to exclusive or shared mode in the Parameter File (Example:
REMOTE_LOGIN_PASSWORD=EXCLUSIVE).

Q: How do you create a password file?


A: To create the password file, you should run the ORAPWD utility from operating
system.
For example:
MS-DOS> ORAPWD FILE=%ORACLE_HOME\dbs\orapw<sid>.pwd \
PASSWORD=mypass ENTRIES=3
The ENTRIES parameter specifying the number of user entries allowed for the password
file. Now, the DBA can be connected to the database as a user with sysdba privilege.

Q: Describe the Online Redo Log file.


A: The Online Redo Log files hold the Redo Entries. You should have at least two or
more Redo Log Groups. Each group may have more than one member. It is a good
practice to multiplex Online Redo Log members. The Redo Entries are information that
will be used to reconstruct, or redo, changes made to a database. The Log Writer writes
the entries into the Online Redo Log files when a COMMIT occurs, every 3 seconds, or
when one third of the Redo Log Buffer is full. That will guarantee a database recovery to
a point of failure if an Oracle database failure occurred.

Q: How do you start up an instance with the MOUNT option?


A: SQL> CONNECT / AS SYSDBA
SQL> STARTUP MOUNT
--OR--
SQL> STARTUP NOMOUNT
SQL> ALTER DATABASE MOUNT;
Q: Describe the IMMEDIATE option in the SHUTDOWN command.
A: The IMMEDIATE option means not to wait for a user to log off and roll back
uncommitted transactions, then shut down the instance and close the database.

Q: Describe the ABORT option in the SHUTDOWN command.


A: The ABORT option tells Oracle not to wait for a user and do not roll back for any
transaction and shutdown the instance. If you SHUTDOWN with the ABORT option and
then you start your database, the SMON will perform an instance recovery automatically.

Q: Describe the PFILE parameter in the STARTUP command.


A: It tells the Oracle to use the specific parameter file that is in the PFILE parameter.

Q: What does the following SQL statement?


SQL> ALTER DATABASE BACKUP CONTROLFILE
TO 'c:\backupcontrolfile\control_ddmmyyyy.ctl'
/
A: It will backup a controlfile.

Q: What is the ALERT file in an Oracle database?


A: It is a log file that any unknown problems with the database such as, not enough
space in the rollback segment or the maximum extent reached in a table.

Q: How many different types of database mode can you change your database to?
A: Six! ARCHIVELOG, NOARCHIVELOG, SUSPEND, RESUME, RESTRICTED
SESSION, and QUIESCE RESTRICTED mode.

Q: What does the following statement do?


SQL> CREATE SPFILE
FROM
PFILE='%ORACLE_HOME%\admin\school\pfile\init.ora'
/
A: It creates a Server Parameter File using an specific parameter file.

Q: How do you configure a database to an archive mode?


A: First you should change the following parameters in the parameter file.
log_archive_dest = /u01/app/oracle/admin/<database_name>/arch
log_archive_start = true
log_archive_format = log%s.arc
Then do the following in the SQLPLUS utility.
SQL> SHUTDOWN IMMEDIATE
SQL> STARTUP MOUNT
PFILE=%ORACLE_HOME%\admin\school\pfile\init.ora
SQL> ALTER DATABASE ARCHIVELOG;
SQL> ALTER DATABASE OPEN;
Q: What does the following SQL statement?
SQL> ALTER DATABASE RENAME FILE
'C:\ORACLE\ORADATA\SCHOOL\REDO04.LOG' TO
'C:\ORACLE\ORADATA\redo04a.log'
/
A: Assuming that Online Redo Log file is offline, it relocates it to different location.

Q: What are the differences between an Oracle-Managed and User-Managed files?


A: A User-Managed file will be defined by an Oracle user. If you drop the tablespace
that was using the file, you should physically delete it from the disk. But an Oracle-
Managed file will be created and defined by Oracle. If you drop the tablespace that was
using the file, oracle will physically deletes the file from the disk. It knows where the file
is located.

Q: How do you maintain a tablespace using the Oracle-Managed file technique?


A: You should tell Oracle where it should locate and create datafiles.
SQL> ALTER SYSTEM SET db_create_file_dest='c:\newfolder';

Q: What does the following SQL statement do?


SQL> CREATE TEMPORARY TABLESPACE mytemp
TEMPFILE 'mytemp_01.tmp' SIZE 20M
EXTENT MANAGEMENT LOCAL
UNIFORM SIZE 10M
/
A: It creates locally managed temporary tablespace with uniform size option.

Q: What are the PCTFREE and PCTUSED space allocations in the CREATE TABLE
statement?
A: The PCTFREE parameter means that an Oracle user can add records to a block until
the unused space block reaches to the PCTFREE value. When a block uses all space up to
the “1-PCTFREE” percentage, it stops adding records to the block. Oracle takes that
block out of the Freelist. It means that records can not be added to the block any more
unless you delete records from the block till it reaches to the PCTUSED value. Then
Oracle will add the block in the Freelist again and records can be added to the block. And
this process continues to determine when to add records in or stop adding records from
the block.

Q: How do you create an UNDO tablespace?


A: SQL> CREATE UNDO TABLESPACE my_undo_tablespace
DATAFILE SIZE 100K
/

Q: What are the differences between a DICTIONARY-MANAGED and LOCALLY


managed tablespace?
A: The difference between the DICTIONALY-MANAGED and LOCALLY
MANAGED tablespace is: In the locally managed tablespace all information about the
datafiles such as the last performed checkpoint, etc are stored locally in the datafiles of
the tablespace but in the DICTIONAY-MANAGED tablespace all such information
would be stored in the Oracle repository in the SYSTEM tablespace.

Q: How do you create a TRANSACTION temporary table?


A: SQL> CREATE GLOBAL TEMPORARY TABLE test_temp
(col1 NUMBER(5) PRIMARY KEY,
col2 VARCHAR2(10) check (col2 BETWEEN 'A' AND 'T'))
ON COMMIT DELETE ROWS
/

Q: What are the differences between a row migration and chained record?
A: A “Chained Record” happens when a user updates a record and the new value can
not fit in the existing allocated location. So, Oracle stores the value in a space that
allocated for them (PCTFREE) and add a pointer to the row so that it knows where the
rest of the record is. This process calls row Chaining. Now, if there was no space in the
PCTFREE area, then Oracle will take the whole record and migrate it in a different block
that has space. This process calls row Migration.

Q: How do you monitor a usage of an index table?


A: SQL> ALTER INDEX uk_emp
MONITORING USAGE
/

Q: What does the EXCEPTIONS INTO EXCEPTIONS clause perform in the ALTER
TABLE statement?
A: It will insert all exceptions that were found during the ALTER TABLE command
into the EXCEPTIONS table.

Q: How do you create a user account?


A: SQL> CREATE USER developer
IDENTIFIED BY developer
DEFAULT TABLESPACE iself_data
TEMPORARY TABLESPACE temp
QUOTA 10K ON iself_data
QUOTA 0K ON SYSTEM
PROFILE default
PASSWORD EXPIRE
ACCOUNT UNLOCK
/

Q: How do you assign a default tablespace to a user?


A: SQL> ALTER USER developer
DEFAULT TABLESPACE iself_data
/

Q: How do you lock a user?


A: SQL> ALTER USER DEVELOPER ACCOUNT LOCK
/

Q: What are the Oracle database triggers?


A: The Oracle database triggers are triggers that will occur when an Oracle event
happens either by the DML statements such as UPDATE, DELETE , INSERT, etc; the
DDL statements such as DROP, CREATE, etc; the Database events such as
SHUTDOWN, STARTUP, etc; or events in a schema such as dropping a table in an
specific schema.

Q: How do you start or stop auditing?


A: SQL> ALTER SYSTEM SET audit_trail=db SCOPE=spfile
/
and you should shutdown and startup the database.

Then start auditing by using the AUDIT command.


Ex: SQL> AUDIT DELETE
ON iself.emp
BY ACCESS
WHENEVER SUCCESSFUL
/

And stop auditing by using the NOAUDIT command.


Ex: SQL> NOAUDIT ALL
/

Q: What is a cluster table in the Oracle database?


A: A cluster is a schema object that contains one or more tables that all have one or
more columns in common. Rows of one or more tables that share the same value in these
common columns are physically stored together within the database. Generally, you
should only cluster tables that are frequently joined on the cluster key columns in SQL
statements. Clustering multiple tables improves the performance of joins, but it is likely
to reduce the performance of full table scans, INSERT statements, and UPDATE
statements that modify cluster key values.

Q: How do you re-organize all a schema’s tables?


A: SQL> EXECUTE dbms_stats.gather_schema_stats ('your_schema_name');
Oracle DBA #2 Fundamental Exam
Answers
NOTE: The answers go with their sequences. If a question was not answer, that means
that
it a repeating question and the answer was given by the previous questions or it is not in
the
scope of this subject.

“We promise according to our hopes and perform according to our fears.”

Francois De La Rochefoucauld 1613-1680


Answers:
Q: What are the Oracle Background Processes?
A: The Oracle Background Processes are programs or tasks that run on the Oracle
background
such as log writers, db writers, archives, checkpoint, etc.

Q: Describe the V$BGPROCESS view.


A: The V$BGPROCESS view contains information about active and inactive
background processes.

Q: Describe the following background processes:


PMON
DBWn
ARC0
CKPT
LGWR
SMON
RECO
A: PMON - The Process Monitor (PMON) is responsible for performing recovery if a
user
process fails and rolls back the uncommitted transactions. DBWn - The Database Writer
(DBWn) is responsible for writing the changed blocks or dirty blocks in the database.
ARC0 - The Archiver (ARC0) is responsible for writing the Online redo log files into
the
archive log destination. CKPT - The checkpoint process (CKPT) is responsible for
synchronizing the buffer cache with the data file. It updates all datafile headers and the
control files. LGWR - The Log Writer (LGWR) is responsible for writing data from
redo
log buffers to the online redo log files. SMON - The System Monitor process (SMON)
is responsible for instance recovery. RECO - The Re-coverer Process (RECO) is
responsible for performing recovery of in-doubt transactions that often occur in
distributed
transactions.

Q: Describe an archive log configuration.


A: In an archive log configuration, Oracle grantees to recover to the point of failure.

Q: What does the ARCHIVE LOG LIST command?


A: The ARCHIVE LOG LIST command shows information about the database archive
log mode status.

Q: What are disadvantage and advantage of a database in the NOARCHIVELOG mode?


A: Disadvantage: You can’t recover to the database point of failure. Advantage: It
will
use fewer resources.

Q: What are disadvantage and advantage of a database in the ARCHIVELOG mode?


A: Advantage: You can recover to the database point of failure. Disdvantage: It will
use
more resources.

Q: What does the following SQL statememt?


SQL> SELECT * FROM v$bgprocess
WHERE PADDR <> '00'
/
A: It shows all the active Oracle background processes.

Q: How do you test that a database is in archivelog or not?


A: SQL> ARCHIVE LOG LIST

Q: What is the controlfile in the Oracle database?


A: The controlfile in the Oracle database is a binary file that contains the database
structure,
backup information, datafiles synchronization, and more.

Q: How do you get a list of all your controlfiles’ location?


A: SQL> SELECT name
FROM v$controlfile

Q: Describe the following views:


V$CONTROLFILE view
V$CONTROLFILE_RECORD_SECTION view
A: The V$CONTROLFILE view contains the location of your controlfiles and their
status.
The V$CONTROLFILE_RECORD_SECTION view shows different section
information
such as record_size, records_total, records_used, etc.

Q: What do the following SQL statements?


SQL> ALTER DATABASE BACKUP CONTROLFILE
TO 'c:\backupcontrolfile\control_ddmmyyyy.ctl'
A: Copies controlfile exactly as it was on the time of its backup.
SQL> ALTER DATABASE BACKUP CONTROLFILE TO TRACE
A: Gets a SQL statement. We can use it to re-create the controlfile if we needed.
SQL> SELECT * FROM v$controlfile_record_section
A: Queries information about different section in the controlfile.

Q: You, as a DBA, are responsible to multiplex controlfiles to protect your organization


from a possible and unexpected loss of controlfiles, due to media failure. You task is to
add
one more controlfile to you database. What are the steps?
A:
• Add one more controlfile entry into the parameter file.
• You shut down the database.
• Copy one of the controlfiles to with the new name that was added to the
parameter file.
• Start your database.

Q: How do you configure your database to an archivelog mode?


A:
1- SQL> ALTER DATABASE CLOSE
2- SQL> ALTER DATABASE ARCHIVELOG
3- Add the following statement into your parameter file.
Log_archive_start=true
log_archive_dest=’c:\archivelogs’
log_archive_format=’arc%S.%T’
4- SQL> ALTER DATABASE OPEN

Q: How do you query your database’s archive log information?


A: SQL> ARCHIVE LOG LIST

Q: How do you set an archive log destination?


A: SQL> ALTER SYSTEM ARCHIVE LOG START TO 'c:\archivelogs';

Q: What is the Server Parameter file (SPFILE)?


A: The Server Parameter File (SPFILE) is the same as the database parameter file. The
only
difference is: it is in a binary format code and can not be read or edited. It is used to
change
the Oracle system parameters dynamically by using the ALTER SYSTEM SET
command.

Q: What do the following statements do?


ALTER SYSTEM SET log_archive_start=true SCOPE=spfile
A: It changes the archive log automatic start.
ALTER SYSTEM SET log_archive_dest='c:\archivelogs' SCOPE=spfile
A: It changes the archive log destination dynamically.
ALTER SYSTEM SET log_archive_format='arc%S.%T' SCOPE=spfile
A: It changes the archive log format dynamically.

Q: You, as a DBA, are responsible to recover any failures to a point of failure and also
to
perform your backup while in online status. Your shop is 24x7 and you are not able to
shutdown the database. Therefore, the database has to be in an archive mode. You should
change you database mode from noarchivelog to archivelog mode. What are the steps
that you should perform to change your database mode?
A:
1- SQL> ALTER DATABASE CLOSE
2- SQL> ALTER DATABASE ARCHIVELOG
3- Add the following statement into your parameter file.
Log_archive_start=true
log_archive_dest=’c:\archivelogs’
log_archive_format=’arc%S.%T’
4- SQL> ALTER DATABASE OPEN

Q: Describe an online redo log file in a database.


A: The online redo log files are used to store Oracle user’s entries; and once it is full,
the file
will be archived to an assigned destination in the Oracle database. The log writer process
writes those users entries from the redo log buffer.

Q: How do you add a redo log file group 3 to a database structure?


A: SQL> ALTER DATABASE ADD LOGFILE
GROUP 3 SIZE 2M;

Q: How do you resize a redo log file?


A: You should remove the redo log file and then re-create it with a new size.

Q: How do you drop a redo log file 3?


A: You can drop the online redo log groups that bear the status of INACTIVE.
SQL> ALTER DATABASE DROP LOGFILE
GROUP 3;

Q: Describe the V$LOG and V$LOGFILE views.


A: Note that the V$LOG dictionary view contains information such as its group
number,
size, member, status, archived, and the first change number in the log. The V$LOGFILE

dictionary view contains the location of logs and their status.

Q: What does the following SQL statement?


SQL> SELECT * FROM v$archived_log
WHERE recid >
(SELECT MAX(recid) - 10 FROM v$archived_log)
/
A: Queries the last 10 archived logs.

Q: You, as a DBA, are responsible to maintain and relocate the Redo Log files in order
to
distribute data among multiple hard disks to increase I/O performance. Your task is to
relocate
only of the redo log file from it original location c:\orignial_location to c:\newlocation
sub-directory.
What are the steps?
A:
• Check the status of its group, if it is inactive then drop it.
• Create an online redo log group with the same group number.

Q: How do you set an Oracle-Managed archive log file destination?


A: SQL> ALTER SYSTEM SET log_archive_duplex_dest='c:\my2ndArclogs';

Q: Describe an Oracle-Managed File (OMF).


A: An Oracle-managed file is a file that Oracle takes control to manage it.

Q: What are the following views?


V$ARCHIVE_DEST view
V$ARCHIVED_LOG view
V$LOG_HISTORY view
A: The V$ARCHIVE_DEST view shows information about archive destinations.
The V$ARCHIVED_LOG view shows all created archived log information.
The V$LOG_HISTORY view shows that what was the first change number on that log.
Q: What is the Sequence Archive log number?
A: It is a number that will be assigned for each archived log file.

Q: You, as a DBA, are responsible to duplex archived Online Redo log files in order to
protect the organization from a loss of or a case of corrupted archived files. Take one of
the redo log file group and add a member to it in a different disk. What are the steps?
A:
1- SQL> SHOW PARAMETER %archive%dest
2- SQL> HOST MKDIR c:\my2ndArclogs
3- SQL> ALTER SYSTEM SET log_archive_duplex_dest='c:\my2ndArclogs';

Q: How many backup do we have?


A: Two! They are the Physical and Logical backups. The physical backup can be
performed
as a COLD backup or HOT backup. The logical backup can be performed while the
Oracle
database is running using the EXP command.

Q: What is a cold or offline database backup?


A: It is a part of the recovery process and will be performed when the Oracle database
is
shutdown with immediate, transactional or normal options.

Q: Describe a usage of the following views:


V$DATABASE view
V$LOGFILE view
V$DATAFILE view
V$CONTROLFILE view
A: The V$DATABASE view contains information about the Oracle database such as
the
database id, name, created date, database mode, log mode, etc. The V$LOGFILE view
contains information about the location of logs, their status, etc. The V$DATAFILE
view
contains information about datafiles’ location, their status, etc. The V$CONTROLFILE

view contains information about controlfiles’ location, their status, etc.

Q: To perform a COLD backup, does the database need to be in an archivelog mode?


A: No.

Q: You, as a DBA, are responsible to backup the database and restore the data in case of
a
loss of data due to media failure. Based on your organization’s business rules, the
database can
be shutdown every day for 5 hours. You also know the backup won’t take more than an
hour.
You want to use the COLD backup process once a day. Write a script to perform a
complete
cold backup.
A: SQL> SET ECHO OFF
SQL> SET HEADING OFF
SQL> SET FEEDBACK OFF
SQL> SET PAGESIZE 1000
SQL> SPOOL c:\userbkup\my_COLD_bkup.sql
SQL> SELECT 'HOST COPY ' || name || ' c:\userbkup\*;'
FROM v$controlfile;
SQL> SELECT 'HOST COPY ' || name || ' c:\userbkup\*;'
FROM v$datafile;
SQL> SELECT 'HOST COPY ' || member || ' c:\userbkup\*;'
FROM v$logfile;
SQL> SELECT ‘HOST COPY \
‘%ORACLE_BASE\admin\school\pfile\init.ora \
c:\userbkup\*;’ FROM dual;
SQL>
SQL> SPOOL OFF
SQL> SET HEADING ON
SQL> SET FEEDBACK ON
SQL> SET PAGESIZE 55
SQL> SET ECHO ON

Q: What is a HOT or OFFLINE backup


A: It is a part of the recovery process and will be performed when the Oracle database is
running.

Q: Describe the DBA_DATA_FILES dictionary view.


A: This dictionary view provides datafiles’ statistics information.

Q: How do you perform a hot backup on a tablespace?


A: We backup one tablespace at a time:
1- ALTER TABLESPACE mytablespace BEGIN BACKUP;
2- Copy all its datafiles’ locations.
3- ALTER TABLESPACE mytablespace END BACKUP;

Q: What are the differences between a hot and cold backup?


A: The Oracle database must be closed before performing a COLD backup but while
you are
performing a HOT backup; your database doesn’t need to be closed.

Q: What do the following SQL statements?


SQL> ALTER TABLESPACE tools BEGIN BACKUP;
A: Put all the tablespace’s datafiles in the backup mode and don’t apply any changes to
the
datafiles unless I end the backup mode.
SQL> HOST COPY \
C:\ORA9I\ORADATA\SCHOOL\TOOLS01.DBF \
C:\userhotbkup\*
A: Start copying or backing up all the tablespace’s datafiles.
SQL> ALTER TABLESPACE tools END BACKUP;
A: End the tablespace backup mode.

Q: Describe the V$DATAFILE and DBA_DATA_FILES dictionary views?


A: See the above descriptions.

Q: Describe the TOTAL PAGES FAILING output from dbv utility.


A: If the TOTAL PAGES FAILING values are greater zero when you perform the
DBV
command, it means there are problems in the datafile. You should only perform the
ONLINE
tablespace backup when the tablespace’s datafile values are zero.

Q: How do you OFFLINE a tablespace?


A: SQL> ALTER TABLESPACE users OFFLINE;

Q: How many different OFFLINE option do you have for a tablespace?


A: The NORMAL (default option), TEMPORARY or IMMEDIATE options. Note that
if you use the TEMPORARY or IMMEDIATE options for OFFLINE, you will not be
able
to get the tablespace ONLINE unless you perform a media recovery.

Q: How do you perform an integrity check on a datafile?


A: MS-DOS> dbv file=C:\ORACLE\ORA90\SCHOOL\USERS01.DBF -
BLOCKSIZE=4096

Q: What does the dbv utility?


A: It performs an integrity check on a datafile.

Q Can you ONLINE a tablespace that was OFFLINE with the TEMPORARY or
IMMEDIATE options?
A: No, unless you perform a media recovery.

Q: You, as a DBA, are responsible to backup the tablespace or datafile and restore the
data to the point of failure in case of a loss of data due to a media hard disk crash. Your
organization is a 24x7 day shop and you are not able to shutdown the database. You have
to use HOT or ONLINE backup. How do you perform a tablespace backup?
A:
4- ALTER TABLESPACE mytablespace BEGIN BACKUP;
5- Copy all its datafiles’ locations.
6- ALTER TABLESPACE mytablespace END BACKUP;
-- OR --
7- ALTER TABLESPACE mytablespace OFFLINE;
8- Copy all its datafiles’ locations.
9- ALTER TABLESPACE mytablespace ONLINE;

Q: How do you store a destroyed datafile when Oracle is online and running?
A:
1- Offline the tablespace.
2- Restore the tablespace’s datafile or datafiles.
3- Recover the tablespace.
4- Online the tablespace.

Q: How do you recover a tablespace?


A: SQL> RECOVER TABLESPACE mytablespqace;

Q: What does the following SQL statement?


SQL> RECOVER TABLESPACE users;
A: It recovers the USERS tablespace.

Q: You, as a DBA, are responsible to recover the database to the point of failure due to
a loss of data and a media failure. Assuming that you lost your TOOLS’s datafiles, what
are the steps to recover the datafiles to the point of failure?
A:
1- ATLER TABLESPACE tools OFFLINE;
2- Restore the tablespace datafile or datafiles.
3- RECOVER TABLESPACE tools;
4- ALTER TABLESPACE tools ONLINE;

Q: What is a physical backup?


A: A physical backup is one of a database recovery steps that is performed based
on a database physical layout.

Q: What is a logical backup?


A: A logical backup is one of a database recovery steps that is performed based
on a database logical layout.

Q: How do you perform a logical backup?


A: MS-DOS> exp
Q: How do you perform a logical restore?
A: MS-DOS> imp

Q: You, as a DBA, are responsible to perform a logical backup using the EXP tool.
Notice that if the loss of data since the last time of backup is not significant then a
logical
backup is a good option to use. Scott lost its EMP table and you have been tasked to
restore it using the IMP utility.
A: MS-DOS> IMP userid=… file=myexport.dmp tables=EMP

Q: What are the steps to perform an automated Oracle COLD backup?

A:

1- Shutdown the database,


2- Backup the database files,
3- Startup the database.
Q: What does the UTL_FILE_DIR parameter?
A: This parameter gives permission to Oracle to write or read from defined directory.

Q: What does the following SQL statements do?


GRANT

SELECT ON v_$datafile TO xxx;


GRANT

SELECT ON v_$logfile TO xxx;


GRANT

SELECT ON v_$controlfile TO xxx;


GRANT

You might also like