Professional Documents
Culture Documents
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: 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 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: 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.
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: 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: 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 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 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.
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: 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: 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.
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: 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 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: 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: 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 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: 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: 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: 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: 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: What are the differences between a private synonym and public synonym?
A: The private synonym can not be accessed by public.
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 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: Where do you save the package body and its package specification?
A: You can store them either in the client or server environments.
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;
/
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: 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: 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: 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.
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: 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: 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: 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;
/
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: 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: 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: 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 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: 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 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: 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.
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: 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 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: 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: 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.
“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 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: 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 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: 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 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: 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: 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: 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: 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: 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: Can the above new user access to any other user tables?
A: No.
Q: How do you open the SQL Script into the Oracle Buffer?
A: SQL> get c:\myscript.sql
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 use the notepad editor as an independent tool in the SQLPLUS utility?
A: Just open your notepad editor outside of your SQLPLUS.
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: 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 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 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: 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: 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: Can you update, insert, or delete any records while you are using the MERGE
statement?
A: Yes.
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 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 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: 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: 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: 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: 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: 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 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: 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: 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: 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: 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>/
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
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.
REGEXP_LIKE ,
*
REGEXP_REPLACE ,
*
REGEXP_INSTR , and
*
REGEXP_SUBSTR
Syntax
Description
Classification
Dot
a?
a*
Quantifier
a+
Quantifier
a|b
Alternation
a{m}
Quantifier
a{m,}
Quantifier
a{m,n}
Match ‘a’ between m and n times
Quantifier
[abc]
Bracket Expression
(…)
Group an expression
Subexpression
\n
Backreference
[:cc:]
Character Class
[.ce.]
Collation Element
[=ec=]
Match equivalence class in bracket expression
Equivalence Class
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:
Meaning
[:alnum:]
[:alpha:]
[:blank:]
[:cntrl:]
[:graph:]
[:lower:]
[:print:]
[:punct:]
[:space:]
[:upper:]
[:xdigit:]
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’,
FROM dual;
A: Keep this in your mind that these functions support CHAR, VARCHAR2, CLOB,
NCHAR, NVARCHAR, and NCLOB datatypes.
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
FROM dual;
A:
SQL> SELECT
FROM dual;
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
FROM dual;
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:
WHERE REGEXP_REPLACE
You used ‘^’ to indicate that the beginning of the line has to be 199, and [-] with $ to
specify range of valid characters.
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’,
FROM dual;
UNDO Advisor
FROM dba_alert_history
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:
FROM dba_alert_history
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.
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
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%’”
A:
$ impdp
DIRECTORY=private_exp_space
DUMPFILE=expdat01.dmp
SQLFILE=MyScript.sql
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:
ORGANIZATION EXTERNAL
(
TYPE ORACLE_DATAPUMP
LOCATION ( ‘expdat01.dmp’)
PARALLEL AS
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:
$ rman TARGET=/
DB_FILE_NAME_CONVERT =
‘/local/oradata/school/data’ , ‘/remote/oradata/data’;
Backup and Recovery Enhancements
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.
A: To define a Flash Recovery Area set the following Oracle Initialization Parameters.
A:
space_reclaimable, number_of_files
FROM v$recovery_file_dest;
A:
SQL> SELECT object_type, message_type,
FROM dba_outstanding_alerts ;
A:
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:
db_create_file_dest = ‘/u03/oradata/school’;
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:
A:
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:
FROM v$backup_datafile
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.
A:
A:
A:
Q: Use a fast recovery without restoring all backups from their backup location to the
location specified in the controlfile.
A:
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:
A:
A:
space_reclaimable, number_of_files
FROM v$recovery_file_dest;
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.
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:
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.
If you disable the flashback (OFF), all existing Flashback Database logs are deleted
automatically.
A: The FLASHBACK DATABASE command force the database back to a past time or
SCN. See the following examples:
FROM v$flashback_database_log;
A:
FROM v$flashback_database_log;
A: You can use this to adjust the retention time or the flash recovery area size.
A: If you do not want the USER tablespace to be included to log Flashback Database
data, do the following SQL statement.
A:
Q: How can you query the content of the recycle bin by using the DBA_RECYCLEBIN
view?
A:
A: Use the FLASHBACK TABLE command to recover a table and all its possible
dependent objects form the recycle bin.
FROM dba_recyclebin
SQL> PURGE TABLESPACE scott_ts USER scott; -- All the Scott’s objects.
Q: How can you perform queries on the database as of a certain clock time or SCN?
A:
FROM emp
Q: How can you use the CURRENT_SCN column in the V$DATABASE view to
obtain the current SCN?
A:
RETENTION GUARANTEE;
RETENTION GUARANTEE;
A:
A:
Use the FLASHBACK TABLE command to recover a table and all its possible
dependent objects form the recycle bin.
FROM dba_recyclebin
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.
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.
FROM dba_advisor_def_parameters
A: You should type the following SQL statement to display the most recent ADDM
report using a SQL command.
FROM dba_advisor_tasks
or
SQL> @$ORACLE_HOME/rdbms/addmrpt
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.
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.
FROM v$parameter
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 .
A: Automated tasks
Server-Generated alerts
Advisory Framework
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 (
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,
END;
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}.
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.
Use the task name to get the results from the analysis.
‘SYS.ALERT_QUE’, AQ$_AGENT(‘ALERT_MYUSERS’,’’,0));
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.
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 (
END;
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’,
END:
FROM dba_thresholds;
A:
SQL> BEGIN
DBMS_SERVER_ALERT .set_threshold (
DBMS_SERVER_ALERT .user_commits_sec,
NULL,
NULL,
NULL,
NULL,
1, 1, ‘SCHOOL’,
END;
A:
SQL> BEGIN
dbms_aqadm .remove_subscriber(
‘SYS.ALERT_QUE’,AQ$_AGENT(‘ALERT_MYUSER’,’’,0);
END;
Application tuning
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
END;
/ -- Note: you should use GATHER only if you are using release 8i
A:
Create a binding variable and then move your query into it.
SQL> BEGIN
END;
Q: How do you use the DBMS_SQLTUNE package to create a tuning task by calling
the CREATE_TUNING_TASK function?
SQL> BEGIN
END;
SQL> BEGIN
END;
(TASK_NAME=>:my_task)
FROM dual;
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> BEGIN
:my_profile := DBMS_SQLTUNE .accept_sql_profile
END;
A:
SQL> BEGIN
DBMS_RESOURCE_MANAGER .create_plan_directive (
END;
/
Scheduler
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).
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.
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> BEGIN
DBMS_SCHEDULER .create_schedule (
END;
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 (
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 (
END;
SQL> BEGIN
DBMS_SCHEDULER .create_job (
END;
/
You could also use your created schedule:
SQL> BEGIN
DBMS_SCHEDULER .create_job (
END;
Tablespace Monitoring
For example:
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,
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:
FROM dba_thresholds
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’,
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,
END;
A:
FROM dba_alert_history
FROM dba_outstanding_alerts
A: To set the default tablespace type to BIGFILE , you can use either CREATE
DATABASE or ALTER DATABASE.
A:
A:
Q: What are the difference between a BIGFILE rowid and a small file rowid?
A:
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:
A:
A:
Notice, since a bigfile tablespace can contain only one data file, your command should
fail.
A: To get its ROWID, you should use the following database package
(DBMS_ROWID).
FROM test_rowid;
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.
A:
Intermedia, Spatial
*
Scheduler
*
OLAP
*
XML DB
*
Workspace Manager
*
Data Mining
*
Recovery Catalog
*
EM Repository
*
Statspack
Q: How can you monitor the space usage of each occupant inside the SYSAUX
tablespace ?
FROM v$sysaux_occupants
A:
PERMANENT
*
READ WRITE
*
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.
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: 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?
FROM database_properties
WHERE property_name =
‘DEFAULT_PERMANENT_TABLESPACE’
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?
SQL> BEGIN
DBMS_FILE_TRANSFER .COPY_FILE (
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:
A: ASM provides a vertical integration of the file system and the volume manager that
is specifically built for Oracle database files.
A:
Custer-aware
*
Automatically installed
A: ASM instance does not have a data dictionary and it is restricted to few SQL
commands and Dynamic Performance view.
Creating a diskgroup:
‘/dev/rdsk/c0t1d0s2’,
‘/dev/rdsk/c0t2d0s2’
‘/dev/rdsk/c1t0d0s2’,
‘/dev/rdsk/c1t1d0s2’,
‘/dev/rdsk/c1t2d0s2’;
A: Dropping a diskgroup:
SQL> DROP DISKGROUP dgora1 INCLUDING CONTENTS;
A: The following are examples of how to add disks to an existing disk group.
A: To remove a disk:
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.
FROM v$asm_disk
FROM v$asm_file
A: Do the following.
FROM v$asm_disk
/
Execute the following query until you get ‘no rows selected.’
FROM v$asm_operation
FROM v$asm_disk
Now, you should see one more disk was added to disk group.
Security VPD
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
A:
A:
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.
A: Now, you can eliminate previous additional quotation string. See the following
example:
SET comments =
q’X In this example, ‘X’ is used as the quotation mark delimiter. X’;
WHERE ID = 100;
SQL> COMMIT;
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
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:
Portable Clusterware
*
High-Speed InfiniBand Network Support
*
Resource Manager
*
Oracle Streams
*
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.
A:
A:
A:
A:
A:
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
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 ?
Q: How do you import tables from a schema by using the EM Database Control ?
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?
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 ?
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.
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: 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: 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: 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 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: 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: 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.
“We promise according to our hopes and perform according to our fears.”
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: 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: 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: 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 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: 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: 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
A: