Saturday, February 16, 2013

Value based and Fine grained auditing in oracle


A. value base auditing
The standard database auditing just described can catch the fact that a command was executed against a table, but not necessarily the rows that were affected. For example, issuing AUDIT INSERT ON HR.EMPLOYEES will cause an audit record to be generated whenever a row is inserted into the named table, but the record will not include the actual values of the row that was inserted. On occasion, you may want to capture these. This can be done by using  Value-based auditing. It used database triggers for its functioning.

When a user inserts, updates, or deletes data from a table with the appropriate trigger attached, the trigger works in the background to copy audit information toa table that is designed to contain the audit information. Value-based auditing tends to degrade performance more than standard database auditing because the audit trigger code must be executed each time the insert, update, or delete operation occurs.
--creation of trigger_table
SQL> create table system.audit_employees (osuser long, changedt date, ipaddr varchar2(90), newsalary varchar2(500));

Table created.
SQL>

--creation of trigger
SQL> CREATE OR REPLACE TRIGGER system.hrsalary_audit
  2  AFTER UPDATE OF salary
  3  ON hr.employees
  4  REFERENCING NEW AS NEW OLD AS OLD
  5  FOR EACH ROW
  6  BEGIN
  7  IF :old.salary != :new.salary THEN
  8  INSERT INTO system.audit_employees
  9  VALUES (sys_context('userenv','os_user'), sysdate,
 10  sys_context('userenv','ip_address'),
 11  :new.employee_id ||
 12  ' salary changed from '||:old.salary||
 13  ' to '||:new.salary);
 14  END IF;
 15  END;
 16  /

Trigger created.
SQL>

--now if anyone change the salary in the hr.employees table the entry will be made in the system's audit_employees table.

SQL> update hr.employees set salary=4500 where employee_id=124;
1 row updated.

--entries done in the audit table.

SQL> select * from audit_employees;
OSUSER                         CHANGEDT  IPADDR       NEWSALARY
------------------------------ --------- ------------ -------------------------------------
KSNDMCPC2012004\Admin          16-FEB-13              124 salary changed from 5800 to 4500


Fine grained auditing
Database auditing can capture all accesses to a table, whether SELECT or DML
operations. But it cannot distinguish between rows, even though it might well be that
only some rows contain sensitive information.


Fine-grained auditing, or FGA, can be configured to generate audit records only when
certain rows are accessed, or when certain columns of certain rows are accessed
. It can
also run a block of PL/SQL (through audit handler)  code when the audit condition is breached.
FGA is configured with the package DBMS_FGA. To create an FGA audit policy,
use the ADD_POLICY procedure, which takes these arguments:


OBJECT_SCHEMA:- The name of the user who owns the object to be audited. This
defaults to the user who is creating the policy.

OBJECT_NAME:- The name of the table to be audited.
POLICY_NAME:- Every FGA policy created must be given a unique name.
AUDIT_CONDITION:- An expression to determine which rows will generate an audit
record. If left NULL, access to any row is audited.
AUDIT_COLUMN:- A list of columns to be audited. If left NULL, then access to any
column is audited.
HANDLER_SCHEMA:- The username that owns the procedure to run when the audit
condition is met. Default is the user who is creating the policy.
HANDLER_MODULE:- A PL/SQL procedure to execute when the audit condition is met.
ENABLE:- By default, this is TRUE: the policy will be active and can be
disabled with the DISABLE_POLICY procedure. If FALSE, then the ENABLE_POLICY procedure must be used to activate the policy.
STATEMENT_TYPES:- One or more of SELECT, INSERT, UPDATE, or DELETE to define
which statement types should be audited. Default is SELECT only.
AUDIT_TRAIL:- Controls whether to write out the actual SQL statement and its
bind variables to the FGA audit trail. The default is to do so.
AUDIT_COLUMN_OPTS:- Determines whether to audit if a statement addresses any or all
of the columns listed in the AUDIT_COLUMNS argument. Options
are DBMS_FGA.ANY_COLUMNS, the default, or DBMS_FGA_ALL_COLUMNS
The other DBMS_FGA procedures are to enable, disable, or drop FGA policies.
To see the results of fine-grained auditing, query the DBA_FGA_AUDIT_TRAIL view.

For example for FGA auditing click on following link

http://vishwanath-dbahelp.blogspot.in/2011/09/setting-fga-at-schema-level.html





Friday, February 15, 2013

Auditing in Oracle needs to know - part3

Next is privilege level auditing,

B. Auditing on privilege Level
All system privileges can be audited. The different privileges can be selected from system_privilege_map.
Statement and privilege auditing are seperated in the oracle documentation and data dictionary views . However they use identical syntax and considering them as identical will simplify things greater. For example ,

SQL> enabe audit drop any table;

the reflect will populate both in DBA_STMT_AUDIT_OPTS and DBA_PRIV_AUDIT_OPTS .
First note that the AUDIT syntax does not make a distinction between statement
and privilege options. Is “CREATE SESSION” a statement or a privilege option?
What about “DROP ANY TABLE?” According to the Oracle views, each appears
to be both, but only one audit trail record results from each audited action.

Example: auditable system privileges

SQL> conn sys as sysdba
Enter password:
Connected.
SQL> select * from system_privilege_map;

PRIVILEGE NAME
---------- ----------------------------------------
-3 ALTER SYSTEM
-4 AUDIT SYSTEM
-5 CREATE SESSION
-6 ALTER SESSION
-7 RESTRICTED SESSION
-10 CREATE TABLESPACE
-11 ALTER TABLESPACE
-12 MANAGE TABLESPACE
-13 DROP TABLESPACE


..... not entire result is shown ......

-167 GRANT ANY PRIVILEGE
-172 CREATE SNAPSHOT
-173 CREATE ANY SNAPSHOT
-174 ALTER ANY SNAPSHOT
-175 DROP ANY SNAPSHOT
-194 WRITEDOWN DBLOW
-195 READUP DBHIGH
-196 WRITEUP DBHIGH
-197 WRITEDOWN
-198 READUP
-199 WRITEUP


We are giving alter system privileges to test user and enabling audit on it,

SQL> grant alter system to test;

Grant succeeded.

SQL> audit alter system by access;

Audit succeeded.

SQL> select sid, serial# from v$session where username='TEST';

SID SERIAL#
---------- ----------
149 1568

SQL> conn test
Enter password:
Connected.
SQL> alter system kill session '149,1568' immediate;

System altered.

SQL> conn /as sysdba
Connected.
SQL> select username, action_name from dba_audit_trail;

USERNAME                      ACTION_NAME
------------------------------ ----------------------------
TEST                               ALTER SYSTEM
TEST                                LOGOFF BY CLEANUP
TEST                                 LOGOFF

SQL>


C. Auditing on object Level

Objects that can be audited are : tables, views, sequences, packages, stored
procedures/functions. Note that because some objects may be dependant of other
objects (example function -> view -> table ) as a result several audit records
might be inserted when these objects are audited.

Object auditing options are set for all users of the database and cannot be set
for individual users.What options can be set? This can be seen from all_def_audit_opts.

Example object auditing options

SQL> conn sys as sysdba
Enter password:
Connected.
SQL> select * from all_def_audit_opts;

ALT AUD COM DEL GRA IND INS LOC REN SEL UPD REF EXE
--- --- --- --- --- --- --- --- --- --- --- --- ---
-/- -/- -/- -/- -/- -/- -/- -/- -/- -/- -/- -/- -/-

These correspond to the following object options respectively:

alter, audit, comment, delete, grant, index, insert, lock, rename, select, update, reference and execute .

All except reference and execute can be applied to tables, otherwise you will get the error ora-1982 "invalid auditing option for tables".

SQL> audit select on scott.emp by session;


Audit succeeded.

Check: Which objects are audited

SQL> col owner format a7
SQL> col object_name format a7
SQL> select * from dba_obj_audit_opts
where owner='SCOTT' and OBJECT_NAME='EMP';

OWNER OBJECT_ OBJECT_TY ALT AUD COM DEL GRA IND INS LOC REN SEL UPD REF EXE
------- ------- --------- --- --- --- --- --- --- --- --- --- --- --- --- ---
SCOTT EMP TABLE -/- -/- -/- -/- -/- -/- -/- -/- -/- S/S -/- -/- -/-

Generate some audit information:

SQL> connect scott/scott
SQL> select * from emp;
=> all scott.emp's rows are shown
SQL> connect hr/hr
SQL> select * from scott.emp;
=> ERROR at line 1:
ORA-00942: table or view does not exist
SQL> connect system/system
SQL> select * from scott.emp;
=> all scott.emp's rows are shown

Results of auditing:

SQL> connect system/system
SQL> select username, priv_used, ses_actions from dba_audit_object where obj_name='EMP' and owner='SCOTT';

USERNAME    PRIV_USED                  SES_ACTIONS
----------       -------------------           -------------------
SCOTT                                            ---------S------
MAHI            SELECT ANY TABLE      ---------S------
HR                                                  ---------F------
SYSTEM         SELECT ANY TABLE      ---------S------


Auditing in Oracle needs to know - part2

Apart from SYSDBA auditing, Oracle provides three auditing techniques:

1. standart auditing
Auditing based on statement, Privileges and object level. 
In standard auditing we won't get any information of the event like what actually happened on tables ,for example what got inserted or deleted etc . Value-based audit will give this feature .

2. Value-based auditing
Value-based auditing uses database triggers. Whenever a row is inserted, updated,
or deleted, a block of PL/SQL code will run that can (among other things)
record complete details of the event. 

3.Fine-grained auditing
Fine-grained auditing allows tracking access to tables according to which rows
(or which columns of the rows) were accessed. It is much more precise than
either database auditing or value-based auditing, and it can limit the number
of audit records generated to only those of interest.

The standard auditing having 3 levels of auditing:

Statement: Audit all action at any type of objects.
Privilege: audit action on system level privileges
Object_level: Specific audit action lie select, update, insert or delete.
There is no clear cut demarcation between these three auditing , all are some how related to each other.

For all the 3 level of auditing you can choose to audit by access (audit every time you access) or by session (audit only once per access during the session), you can also audit on if the access was successful (whenever successful) or not (whenever not successful)
The difference between BY SESSION and BY ACCESS is that when you specify BY SESSION Oracle will try to merge multiple audit entries into one record when the session and the action audited match.

That is ,
audit by access- audit every time you access- will give accurate picture about what is going on .
audit by session - audit only once per access during the session - Here after session got created and if you are going to insert 100 times on a table ,then it will logged only for the first attempt .

 
CREATE SESSION is a DDL statement Oracle audits this statement by access.

So f
or statement options and system privileges that audit SQL statements other than DDL, you can specify either BY SESSION or BY ACCESS. BY SESSION is the default.

Oracle database can write to an operating system audit file but cannot read it to detect whether an entry has already been written for a particular operation. Therefore, if you are using an operating system file for the audit trail (that is, the AUDIT_TRAIL initialization parameter is set to OS), then the database may write multiple records to the audit trail file even if you specify BY SESSION.
A. statemente level auditing

Statement auditing is the selective auditing of related groups of statements for a type of database structure or type of schema object for ddl (data definition language) or dml (data manipulation language) statements. For example when 'audit table' is audited create , drop and truncate table statements are audited. Statement level auditing is broad .
The statements that can be audited can be seen from stmt_audit_option_map.

SQL> select * from stmt_audit_option_map;

SQL> select * from stmt_audit_option_map where name like '%TABLE%'; etc,

How to use;

SQL> sho user;

USER is "SYS"

SQL> audit table by scott, system; -- ddl level

Audit succeeded.

SQL> conn scott/scott

Connected.

SQL> create table aud_test as select * from EMP;

Table created.

SQL> drop table aud_test;

Table dropped.

SQL>

SQL> alter session set nls_date_format = 'dd-MON-yyyy hh24:mi:ss';

Session altered.

SQL> conn sys as sysdba
Enter password:
Connected.
SQL>  select USERNAME,obj_name,ACTION_NAME,TIMESTAMP from DBA_AUDIT_TRAIL;

USERNAME     OBJ_NAME     ACTION_NAME         TIMESTAMP
------------ ------------ ------------------- --------------------
SCOTT        AUD_TEST     CREATE TABLE        15-FEB-2013 14:02:35
SCOTT        AUD_TEST     DROP TABLE          15-FEB-2013 14:22:32

Statement level auditing at DML level :-
Eg:-
SQL> audit insert table by scott whenever successful;

 Note:- In statement level auditing we are not specifying any object name to audit , that is statement level auditing broad in its audit action .

we can audit the session level event by using following statement audit ,

SQL> conn sys as sysdba
Enter password:
Connected.
SQL> audit session by access;
Audit succeeded.
SQL> conn scott/scott
Connected.
SQL> conn hr/hr
Connected.
SQL> conn sys as sysdba
Enter password:
Connected.
SQL> alter session set nls_date_format = 'dd-MON-yyyy hh24:mi:ss';
Session altered.

SQL>  select username,timestamp,logoff_time,ACTION_NAME from dba_Audit_session;

USERNAME     TIMESTAMP            LOGOFF_TIME          ACTION_NAME
------------ -------------------- -------------------- -------------------
SYSMAN       15-FEB-2013 16:25:18 15-FEB-2013 16:31:29 LOGOFF
SCOTT        15-FEB-2013 16:25:31 15-FEB-2013 16:25:34 LOGOFF
HR           15-FEB-2013 16:25:35 15-FEB-2013 16:26:36 LOGOFF
SQL>

Audit that ebabled on statement level can be viewed by ,

 SQL> select * from DBA_STMT_AUDIT_OPTS;

Note the following views gives you which audits are enabled:
dba_obj_audit_opts
dba_priv_audit_opts
dba_stmt_audit_opts

Disabling Audit:-

The NOAUDIT statement turns off the various audit options of Oracle. Use it to reset statement, privilege and object audit options. A NOAUDIT statement that sets statement and privilege audit options can include the BY USER option to specify a list of users to limit the scope of the statement and privilege audit options.

noaudit table by scott;
noaudit insert table by scott;
noaudit session by access;



Thursday, February 14, 2013

Auditing in Oracle needs to know - part1


No matter how good your security policies are, there will be occasions when a policy is not enough.The most extreme example of this is you, the database administrator. Anyone with the SYSDBA privilege can do anything within the database. So it is necessary to audit all SYSDBA activity. For normal users, you may also wish to track what they are doing. You may not be able to prevent them from breaking company rules on access to data, but you can track the fact that they did it.
Until Oracle 10g, auditing is disabled by default, but can be enabled by setting the AUDIT_TRAIL static parameter in the init.ora file. From Oracle 11g, auditing is enabled for some system level privileges.


SYSDBA auditing
There is an instance parameter AUDIT_SYS_OPERATIONS. If it is set to TRUE (the default is FALSE), then every statement issued by a user connected AS SYSDBA or AS SYSOPER is written out to the operating system’s audit trail. This gives a complete record of all work done by the DBA.Your system needs to be configured in such a way that the DBA has no access to the audit records that track his activity: they should be accessible only to the computer’s system administrator. If the DBA were also the system administrator, then the auditing would be useless.
The destination of the SYS audit records is platform specific. On Windows, it is the Windows Application Log; on Unix it is controlled by the AUDIT_FILE_DEST parameter. This parameter should point to a directory on which the Oracle owner has write permission

How to setup SYSDBA auditing
1. Before setting up any kind of database auditing, an instance parameter must be set: AUDIT_TRAIL. This has four possible values:
NONE (or FALSE) Database auditing is disabled, no matter what auditing you attempt to configure and is default.
OS Audit records will be written to the operating system’s audit trail: the Application Log on Windows, or the AUDIT_FILE_DEST directory on Unix.
DB (or TRUE) The audit records are written to a data dictionary table, SYS.AUD$. There are so many views that let you see the contents of this table.
DB_EXTENDED As DB, but including information on the SQL statements with bind variables that generated the audit records.

Example:-

SQL> sho user;
USER is "SYS"
SQL> select * from v$version;
BANNER
----------------------------------------------------------------
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
PL/SQL Release 10.2.0.4.0 - Production
CORE    10.2.0.4.0      Production
TNS for 64-bit Windows: Version 10.2.0.4.0 - Production
NLSRTL Version 10.2.0.4.0 - Production
SQL> show parameter audit
NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
audit_file_dest                      string      D:\ADMIN\CRAZE\ADUMP
audit_sys_operations                 boolean     FALSE
audit_trail                          string      NONE

SQL> alter system set audit_trail=DB;
alter system set audit_trail=DB
                 *
ERROR at line 1:
ORA-02095: specified initialization parameter cannot be modified

SQL> alter system set audit_trail=DB scope=spfile;

System altered.

SQL> alter system set audit_sys_operations=TRUE scope=spfile;

System altered.

SQL> show parameter audit

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
audit_file_dest                      string      D:\ADMIN\CRAZE\ADUMP
audit_sys_operations                 boolean     FALSE
audit_trail                          string      NONE
SQL>
SQL> shut immediate;
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> startup
ORACLE instance started.
Total System Global Area  931135488 bytes
Fixed Size                  2070096 bytes
Variable Size             285215152 bytes
Database Buffers          637534208 bytes
Redo Buffers                6316032 bytes
Database mounted.
Database opened.
SQL> show parameter audit

NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
audit_file_dest                      string      D:\ADMIN\CRAZE\ADUMP
audit_sys_operations                 boolean     TRUE
audit_trail                          string      DB
SQL> alter user mahi identified by mahi;

User altered.

SQL> alter user mahi default tablespace USERS;

User altered.

SQL>
You can see the activity done by user connected as sysdba in event viewer

Here I usedaudit_trail to DB for my audit purpose .The audit records go to the filesystem (in UNIX) or Event Log (in Windows), not to the database tables, even if the parameter audit_trail is set to DB. The location in UNIX is the filesystem specified by the initialization parameter audit_file_dest, which defaults to $ORACLE_HOME/rdbms/audit.This parameter is independent of the other audit parameter audit_trail. The SYSDBA auditing can be enabled or disabled regardless of whether regular auditing is set.

Thursday, February 7, 2013

How Oracle locks the rows on behalf of the transactions by using ITL

How Oracle locks rows on behalf of transactions? How does the data block grant the locks? Where will it store the locking information for the rows the transaction is asking for? Here comes the structure – Interested Transaction List (ITL). This is a small structure in oracle block, which holds the information about the list of transactions, which are interested in some of the rows of that block. That’s why it’s called Interested Transaction List. ITL is present in the variable portion of the Oracle block. 

 Variable header info grows from the top down (just below the fixed header) if necessary and rows are inserted from the bottom up (just above the tail but depends on PCTFREE and also the size of variable part of data block header cannot exceed 50% of block size. ). It is this portion of data block, which holds the information about locking.

This variable portion of the data block contains slots for transactions to put the locking information. When a row in the block is locked for the first time, the transaction places a lock in one of the slots with the rowid of the row that is locked. In other words, the transaction makes it known that it is interested in the row (hence the name “Interested Transaction List”). When the same transaction or another one locks another row, the information is stored in another slot, and so on.

The next logical question that comes up is, how many slots are typically available? During the table creation, the INITRANS parameter defines how many slots are initially created in the ITL. When the transactions exhaust all the available slots and a new transaction comes in to lock a row, the ITL grows to create another slot. The ITL can grow up to the number defined by the MAXTRANS parameter of the table, provided there is space in the block. Nevertheless, if there is no more room in the block, even if the MAXTRANS is high enough, the ITL cannot grow.

What if there are not enough slots available in ITL? What will happen? Obviously the new transaction asking for the lock on the rows have to wait until the existing transaction is finished and frees up the slot. This is called ITL wait event. Once the existing transaction finishes and frees up the slot, the new transaction can proceed.
When the ITL can’t grow due to the lack of space in the block, the session waits will the event “enq: TX - allocate ITL entry”


ITL Wait in detail
Let’s see this description of the wait in action. Assume our table has INITRANS of one and MAXTRANS 11. A typical data block right after the creation of the table will look like figure 1 below.
Since the INITRANS is one, there is only one slot for the ITL. The rest of the block is empty. Now we inserted three rows into the table. These will go into this block, and the block will look like figure 2.
Note how the empty space is reduced. At this point, a transaction called Txn1 updates Row1, but does not commit. This locks Row1, and the transaction places the lock in the slot number one in the ITL as shown in figure 3.
Then another transaction, Txn2, updates the row Row2 and wants to lock the row. However, there are no more slots in the ITL available to service the transaction. The MAXTRANS entry is 11, meaning the ITL can grow up to 11 slots and the block has empty space. Therefore, ITL can grow by another slot and Slot number two is created and allocated to Txn2 (refer to figure 4).
Now the empty space in the block is severely limited, and it will not be able to fit another ITL slot. If at this time another transaction comes in to update the row three, it must have a free slot in the ITL. The MAXTRANS is 11 and currently only two slots have been created, so another one is possible; but since there is no room in the block to grow, the slot can’t be created. Therefore, the Txn3 has to wait until either of the other transactions rolls back or commits and the slot held by it becomes free. At this time the session will experience an ITL waits event as seen from the view V$SESSION_WAIT.
How to Reduce ITL Waits
The primary cause of ITL waits is the unavailability of free slots in the ITL. These can be due to ,

Low setting of the MAXTRANS, which places a hard limit on the number of transactions that can have locks on a block or, the block is so packed that there is no room for the ITL to grow OR both .Therefore, setting a high value of INITRANS will make sure that there are enough free slots in the ITL and there will be minimal or no dynamic extension of the ITL. However this also means that there is less space in the block for actual data, increasing wasted space.

Note:- MAXTRANS parameter starting from 10G is deprecated.Whatever value we set it is completely ignored by oracle.

Source:- http://avdeo.com  , http://www.proligence.com/itl_waits_demystified.html


Wednesday, February 6, 2013

what is PCTFREE , PCTUSED and FREELIST in oracle

Before discussing with PCTFREE and PCTUSED we need to understand the structure of a database block.
Overview of Data Blocks

Oracle manages the storage space in the datafiles of a database in units called data blocks. A data block is the smallest unit of data used by a database. In contrast, at the physical, operating system level, all data is stored in bytes. Each operating system has a block size. Oracle requests data in multiples of Oracle data blocks, not operating system blocks. The Oracle data block format is similar regardless of whether the data block contains table, index, or clustered data. Below illustrates the format of a data block.


Description of Figure 2-2 follows

Header (Common and Variable)

The header contains general block information, such as the block address and the type of segment (for example, data or index).

Table Directory

This portion of the data block contains information about the table having rows in this block.

Row Directory

This portion of the data block contains information about the actual rows in the block (including addresses for each row piece in the row data area).

After the space has been allocated in the row directory of a data block's overhead, this space is not reclaimed when the row is deleted. Therefore, a block that is currently empty but had up to 50 rows at one time continues to have 100 bytes allocated in the header for the row directory. Oracle reuses this space only when new rows are inserted in the block.

Overhead

The data block header, table directory, and row directory are referred to collectively as overhead. Some block overhead is fixed in size; the total block overhead size is variable. On average, the fixed and variable portions of data block overhead total 84 to 107 bytes.

Row Data

This portion of the data block contains table or index data. Rows can span blocks.

Free space

Free space is allocated for insertion of new rows and for updates to rows that require additional space (for example, when a trailing null is updated to a nonnull value).

In data blocks allocated for the data segment of a table or cluster, or for the index segment of an index, free space can also hold transaction entries. A transaction entry is required in a block for each INSERT, UPDATE, DELETE, and SELECT...FOR UPDATE statement accessing one or more rows in the block. The space required for transaction entries is operating system dependent; however, transaction entries in most operating systems require approximately 23 bytes.


The PCTFREE parameter 


The PCTFREE parameter sets the minimum percentage of a data block to be reserved as free space for possible updates to rows that already exist in that block. For example, assume that you specify the following parameter within a CREATE TABLE statement:

PCTFREE 20 

This states that 20% of each data block in this table's data segment be kept free and available for possible updates to the existing rows already within each block. New rows can be added to the row data area, and corresponding information can be added to the variable portions of the overhead area, until the row data and overhead total 80% of the total block size.Below figure illustrates PCTFREE.

Description of Figure 2-3 follows


The PCTUSED Parameter

The PCTUSED parameter sets the minimum percentage of a block that can be used for row data plus overhead before new rows are added to the block. After a data block is filled to the limit determined by PCTFREE, Oracle considers the block unavailable for the insertion of new rows until the percentage of that block falls beneath the parameter PCTUSED. Until this value is achieved, Oracle uses the free space of the data block only for updates to rows already contained in the data block. For example, assume that you specify the following parameter in a CREATE TABLE statement:

PCTUSED 40 


In this case, a data block used for this table's data segment is considered unavailable for the insertion of any new rows until the amount of used space in the block falls to 39% or less (assuming that the block's used space has previously reached PCTFREE). Until reaching this value oracle utilize the free space for the updation of existing rows .Below figure illustrates this.

Description of Figure 2-4 follows

How PCTFREE and PCTUSED work together


PCTFREE and PCTUSED work together to optimize the use of space in the data blocks of the extents within a data segment. Below figure illustrates the interaction of these two parameters.

Description of Figure 2-5 follows

In a newly allocated data block, the space available for inserts is the block size minus the sum of the block overhead and free space (PCTFREE). Updates to existing data can use any available space in the block. Therefore, updates can use the space once it falls below PCTFREE, the space reserved for updates but not accessible to inserts.

A FREELIST is where Oracle keeps tracks of blocks under the high-water mark for an object. Each will have at least one FREELIST associated with it. As blocks are used, they will be placed or taken off the FREELIST as needed. It is important to note that only blocks under the high-water mark of an object will be found on the FREELIST. The blocks that remain above the high-water mark will be used only when the FREELISTS are empty. In this fashion, Oracle postpones increasing the high-water mark for an object until it must.An object may have more than one FREELIST. If you anticipate heavy insert or update activity on an object by many concurrent users, configuring more than one FREELIST can make a major positive impact on performance (at the cost of possible additional storage). Individual sessions will be assigned to different FREELISTS, and when they need space, they will not contend with each other.

For each data and index segment, Oracle maintains one or more free listslists of data blocks that have been allocated for that segment's extents and have free space greater than PCTFREE. These blocks are available for inserts. When you issue an INSERT statement, Oracle checks a free list of the table for the first available data block and uses it if possible. If the free space in that block is not large enough to accommodate the INSERT statement, and the block is at least PCTUSED, then Oracle takes the block off the free list. Multiple free lists for each segment can reduce contention for free lists when concurrent inserts take place.
After you issue a DELETE or UPDATE statement, Oracle processes the statement and checks to see if the space being used in the block is now less than PCTUSED. If it is, then the block goes to the beginning of the transaction free list, and it is the first of the available blocks to be used in that transaction. When the transaction commits, free space in the block becomes available for other transactions.

An object may have more than one FREELIST. If you anticipate heavy insert or update activity on an object by many concurrent users, configuring more than one FREELIST can make a major positive impact on performance (at the cost of possible additional storage). Individual sessions will be assigned to different FREELISTS, and when they need space, they will not contend with each other.  Every segment will have 1 freelist by default .If there is only one FREELIST, only one transaction at a time may review and modify this list—they would have to wait for each other. Multiple FREELISTS and FREELIST GROUPS serve the purpose of increasing concurrency in such a case, as the transactions may each be looking at different lists and not contending with each other.

Monday, February 4, 2013

Some good question and answer from 10g OCP Certification Exam Guide part 1

PART1 

Question  1. Which of the following commands will start the iSQL*Plus server process?
(Choose the best answer.)
A. emctl start isqlplus
B. isqlplusctl start
C. isqlplus /nolog
D. lsnrctl start isqlplus

2. You issued the URL http://127.0.0.1:5500/em and received an error. What
could be the problem? (Choose three answers.)
A. You have not started the Database Listener
B. You have not started the dbconsole.
C. The dbconsole is running on a different port.
D. You are not logged onto the database server node.
E. You have not started the Grid Control agent.
F. You have not started the database.

3. Which files must be synchronized for a database to open? (Choose the best
answer.)
A. Datafiles, online redo log files, and the controlfile
B. The parameter file and the password file
C. All the multiplexed controlfile copies
D. None. SMON will synchronize all files by instance recovery after opening
the database.

4. During the transition from NOMOUNT to MOUNT mode, which file or files
are required? (Choose the best answer.)
A. Parameter file
B. Controlfiles
C. Online redo logs
D. Datafiles
E. All of the above

5. You shut down your instance with SHUTDOWN IMMEDIATE. What will
happen on the next startup? (Choose the best answer.)
A. SMON will perform automatic instance recovery.
B. You must perform manual instance recovery.
C. PMON will roll back uncommitted transactions.
D. The database will open without recovery.

6. You have created two databases on your computer and want to use Database
Control to manage them. Which of the following statements are correct?
(Choose two answers.)
A. You cannot use Database Control, because it can manage only one
database per computer.
B. You must use Grid Control, as you have multiple databases on the
computer.
C. You must start one OC4J process and contact it on different ports for each
database.
D. You must start one OC4J instance per database.
E. You must set the ORACLE_SID variable appropriately before starting an
OC4J instance.

7. You issue the command SHUTDOWN, and it seems to hang. What could be
the reason? (Choose the best answer.)
A. You are not connected as SYSDBA or SYSOPER.
B. There are other sessions logged on.
C. You have not connected with operating system or password file
authentication.
D. There are active transactions in the database; when they complete, the
SHUTDOWN will proceed.

8. What action should you take after terminating the instance with SHUTDOWN
ABORT? (Choose the best answer.)
A. Back up the database immediately.
B. Open the database and perform database recovery.
C. Open the database and perform instance recovery.
D. None, but some transactions may be lost.
E. None. Recovery will be automatic.

9. Using Database Control, you stop the Database Listener. Which of the
following statements is true? (Choose the best answer.)
A. Database Control will no longer be able to manage the database.
B. Existing sessions will be terminated.
C. No new sessions can be established.
D. You must restart the listener with the lsnrctl utility.

10. Database Control is a multitier web application. Which tier is responsible for
window management? (Choose the best answer.)
A. The dbconsole middle tier
B. The procedures within the database tier
C. The client browser
D. The OC4J application runtime environment


Answers

1. B. The emctl command is used to start the dbconsole, lsnrctl is used to start
database listeners, and isqlplus from a command line won’t do anything.

2. B, C, and D. Any of these could be a reason. A, E, and F are related to other
processes.

3. A. These are the three file types that make up a database: datafiles, online
redo log files, and the controlfile.

4. B. Remember which files are read at each stage: the parameter file at NOMOUNT,
the online redo log files and the datafiles at OPEN.

5. D. This holds true because IMMEDIATE is a clean shutdown.

6. D and E. D is correct because one OC4J can only support one Database Control
process to manage one database, and E is correct because without this the emctl
utility will not know which OC4J to start.

7. B. This answer is correct because the default shutdown mode is NORMAL,
which will wait for all sessions to log off.

8. E. It is vital to remember this!After a crash, or an abort, recovery is automatic
and unstoppable. No data is ever lost, and you need take no action at all.

9. C. Without a listener there is no way to launch the server process needed for
a session.

10. C. Your local window management is done by your local browser. The other
answers refer to processes that reside on the application server tier (A and D),
or within the database (B).

PART2


Questions
1. Which line of code will cause the following SQL statement to fail? (Choose
the best answer.)
1 CREATE BIGFILE TABLESPACE OCP10gDATA
2 DATAFILE '/oracle/ocp10gdata/ocp10gdata02.dbf'
3 EXTENT MANAGEMENT LOCAL
4 FREELISTS 5
5 NOLOGGING;
A. 1
B. 2
C. 3
D. 4
E. 5
F. The statement will succeed

2. You have mounted the database but did not open it. Which views do you
need to query if you need the locations of all datafiles and the names of
the tablespaces they belong to? (Choose all correct answers.)
A. V$DATAFILE

B. DBA_DATA_FILES
C. V$TABLESPACE
D. DBA_TABLESPACES
E. V$TEMPFILE
F. DBA_TEMP_FILES
G. V$UNDOFILE

3. You attempt to create a tablespace but receive an error that the datafile for the
tablespace cannot be created. The size of the datafile you wanted to create is
3GB, and you specified the SMALLFILE option for the tablespace. You verify
that the operating system directory where the file will reside is owned by the
same user as Oracle and the user has full read/write permissions. You are logged
in to the database as the user SYSTEM, and there is plenty of disk space on the
hard drive. What is the likely cause of the error? (Choose the best answer.)
A. You cannot create a file larger than 2GB in an Oracle database when
specifying SMALLFILE.
B. The operating system cannot create a file larger than 2GB.
C. You must specify the WITH OVERWRITE option for the datafile
specification.
D. You must specify the REUSE option for the datafile specification.
E. You must specify the AUTOEXEND option for the datafile specification.


4. You want to be able to re-create a tablespace quickly in case of failure but do
not have the SQL code to perform the operation. What is the best way to
determine which SQL statement will properly re-create the tablespace with
all options correctly set? (Choose the best answer.)
A. Use the Generate DDL option of iSQL*Plus.
B. Use the Generate DDL option of Enterprise Manager.
C. Use the Create Like option of iSQL*Plus.
D. Use the Create Like option of Enterprise Manager.
E. Query the CODE column of the V$TABLESPACE view.
F. Query the TEXT column of the DBA_TABLESPACES view.

5. Which line of code will cause the following SQL statement to fail? (Choose
the best answer.)
1 CREATE BIGFILE TABLESPACE OCP10gDATA
2 DATAFILE '/oracle/ocp10gdata/ocp10gdata02.dbf'
3 EXTENT MANAGEMENT DICTIONARY
4 FREELISTS 5
5 NOLOGGING;
A. 1
B. 2
C. 3
D. 4
E. 5
F. The statement will succeed

6. You determine that a datafile belonging to your ARCHIVE2002 tablespace
is too large. You want to reduce the size of the datafile so that disk space is
not wasted. This tablespace will not have any data added to it. When you
use Enterprise Manager to reduce the size of the datafile belonging to the
tablespace, you receive an error. What is the most likely cause? (Choose
the best answer.)
A. You cannot reduce the size of datafiles in Oracle.
B. You cannot reduce the size of datafiles using Enterprise Manager.
C. You do not have sufficient permissions to reduce the size of the file.
D. The file does not exist.
E. The file contains data beyond the size you want to reduce the file to.

7. You issue the following command to drop a tablespace and receive an error
indicating that the tablespace cannot be dropped. What is the likely cause?
(Choose the best answer.)
DROP TABLESPACE SYSAUX INCLUDING CONTENTS CASCADE CONSTRAINTS;
A. System tablespaces cannot be dropped.
B. You do not have permissions to drop the SYSAUX tablespace.
C. Objects in other tablespaces depend on objects in the tablespace being
dropped.
D. You cannot drop objects in the tablespace that you did not create.
E. The command should succeed.

8. You want to change extent management on your DATA09 tablespace from local
to dictionary to match the other tablespaces in the DATA01–DATA08 range.
Which method can be used to make this change? (Choose the best answer.)
A. DBMS_SPACE_ADMIN.TABLESPACE_DICTIONARY_MANAGED
B. DBMS_SPACE_ADMIN.TABLESPACE_MIGRATE_TO_DICITONARY
C. Enterprise Manager
D. ALTER TABLESPACE DATA09 EXTENT MANAGEMENT DICTIONARY
E. You cannot convert a locally managed tablespace to dictionary
management

9. What permissions are required to create a tablespace? (Choose all correct
answers.)
A. CREATE TABLESPACE
B. MANAGE DATABASE
C. DBA
D. SYSDBA
E. SYSOPER

10. What types of segments can tablespaces in Oracle Database 10g store?
(Choose all correct answers.)
A. Tables
B. Sort segments
C. Redo segments
D. Undo segments
E. DBA segments
F. Clusters

Answers
1. D. When specifying local extent management in the creation of a tablespace,
you cannot specify a dictionary-managed segment storage parameter as well.
FREELISTS can be specified only when extent management is dictionary,
so that part of the CREATE TABLESPACE statement would cause the entire
statement to fail.

2. A, C, and E. Because the database is not yet in an OPEN state, any of the
DBA_ data dictionary views are not yet accessible; they can be queries only
when the database is in an open state. The V$TABLESPACE view will provide
you a list of tablespaces. The V$DATAFILE and V$TEMPFILE views can be
joined to the V$TABLESPACE view using the TS# column to retrieve a list
of all tablespaces and their datafiles. There is no V$UNDOFILE view.

3. D. The most likely reason that you are receiving an error on the creation of
the datafile for the tablespace is that a file with that name already exists. To
correct this, you must specify the REUSE option on the datafile specification
to have Oracle overwrite the existing file (or delete the file manually from the
hard disk). Neither Oracle nor the operating system will prevent a file of 3GB
being created for a SMALLFILE tablespace.

4. B. The Generate DDL option of Enterprise Manager will generate the SQL
code to re-create the selected tablespace. You can then cut and paste this into
a SQL script for later execution. There is no Generate or Create Like option
in iSQL*Plus, and the Create Like option of Enterprise Manager will display
a new page to enter the name of a tablespace with the same parameters as
the one selected. There is no CODE column in the V$TABLESPACE or TEXT
column in DBA_TABLESPACES.

5. C. In order to create a BIGFILE tablespace, you must specify local extent
management and automatic segment space management. You cannot create
a dictionary-managed BIGFILE tablespace.

6. E. Oracle allows you to reduce the size of datafiles, and this can be
accomplished from the command line or using Enterprise Manager. If
you are able to change the size of the file in Enterprise Manager, you have
the necessary permissions to perform the action. The most likely reason
you are unable to perform the action is that more data exists in the datafile
than the size you want to reduce it to. Specify a larger value and try again.

7. A. SYSAUX is a system tablespace and cannot be dropped. The same holds
true for the SYSTEM tablespace.

8. E. Once a tablespace is made locally managed, it is not possible to convert
it to a dictionary-managed tablespace. There is no command or Enterprise
Manager option to perform the change.

9. A and C. You must be granted either the CREATE TABLESPACE system
permission or the DBA role to create a tablespace. There is no MANAGE
DATABASE permission. The SYSOPER and SYSDBA roles provide permissions
for managing the instance and database but do not specifically grant the
holder the permission to create a tablespace.

10. A, B, D, and F. Tablespaces in Oracle can store tables, clusters (both are types
of permanent segments, which also include indexes, partitions, and others),
undo segments, and sort segments (a type of temporary segment). Redo
segments and DBA segments do not exist. Redo is stored in the redo log files.



PART3

Questions


1. You have created a new user called George. You have assigned George the
RESTRICTED_ACCESS user profile. The profile settings have all limits
configured as DEFAULT except for a concurrent sessions limit whose value is
set to 1. George asks you to help with a problem, and when you arrive at his
desk, you notice that he has several SQL*Plus sessions open, all of which are
connected to the instance with his user account. You suspect that your profile
limits are not being enforced. Which of the following should you investigate
to determine the cause of the problem? (Choose two correct answers.)
A. DBA_USER_LIMITS table
B. RESOURCE_LIMIT initialization parameter
C. DBA_PROFILE_LIMITS data dictionary view
D. DBA_PROFILES data dictionary view
E. V$LIMITS dynamic performance view


2. Which line of code will cause the following SQL statement to fail? (Choose
the best answer.)
1 CREATE USER Sam
2 IDENTIFIED EXTERNALLY BY $amP@ssw0rd
3 DEFAULT TABLESPACE Users
4 TEMPORARY TABLESPACE User_Temp
5 QUOTA 2048MB ON APPS_DATA
A. 1
B. 2
C. 3
D. 4
E. 5
F. The statement will succeed

3. You have been asked to provide additional information to your manager on
how system privileges can be assigned and behave. Which of the following
statements about system privileges are true? (Choose all correct answers.)
A. System privileges can be granted to others if you use the WITH ADMIN
OPTION.
B. System privileges can be granted to others if you use the WITH GRANT
OPTION.
C. Only the DBA can grant system privileges, since the DBA owns the database.
D. System privileges can be granted only by the owner of the database.

E. When revoked for a user, system privileges will also be revoked for any
user to whom that revokee granted them.
F. When revoked for a user, system privileges will not be revoked for any user
to whom that revokee granted them.

4. How would a user change his active profile? (Choose the best answer.)
A. ALTER USER SET PROFILE=NewProfile
B. ALTER SYSTEM SET PROFILE=NewProfile
C. ALTER SESSION SET PROFILE=NewProfile
D.
ALTER DATABASE SET PROFILE=NewProfile
E. A user cannot change his active profile

5. If you create a profile and specify limits for only some of the profile settings,
what value will be automatically assigned to any resource limit you do not
include in your CREATE PROFILE statement? (Choose the best answer.)
A. DEFAULT
B. 0
C. UNLIMITED
D. UNKNOWN
E. You must specify a value for all profile limits

6. If you do not specify a TEMPORARY TABLESPACE when creating a new user
account, what will be the value of this parameter when the user is created?
(Choose the best answer.)
A. SYSTEM
B. TEMP
C. NULL
D. Database default temporary tablespace
E. You must specify a value for TEMPORARY TABLESPACE

7. Which of the following commands can a new user called Anthony issue after
successfully connecting to the instance and establishing a user session? (Choose
all correct answers.)
A. ALTER USER Anthony PAS
B. ALTER USER Anthony QUOTA 2M ON SYSTEM;
C. ALTER USER Anthony ACCOUNT LOCK;
D. ALTER USER Anthony TEMPORARY TABLESPACE TEMP;
E. ALTER USER Anthony IDENTIFIED BY NEWPASS;

8. While passing by Benjamin’s desk, you notice that he is using SQL*Plus to
query data in your TempOrders table. You did not grant Benjamin privileges
to issue SELECT statements against your TempOrders table. Why is Benjamin
able to query your table? (Choose all correct answers.)
A. A user to whom you granted the SELECT privilege on the table also granted
it to Benjamin.
B. Benjamin is a DBA and can query any table in the database.
C. You granted Benjamin the UPDATE privilege on the TempOrders table,
which automatically grants the SELECT privilege.
D. Benjamin has been granted the SELECT ANY TABLE privilege by the DBA.
E. Benjamin has been granted the SELECT privilege on your TempOrders
table by a user to whom you granted the SELECT privilege WITH ADMIN
OPTION.

9. Which of the following statements will fail when granting privileges to the
role QueryRole? (Choose the best answer.)
A. GRANT CONNECT TO QueryRole;
B. GRANT CONNECT TO QueryRole WITH ADMIN OPTION;
C. GRANT SELECT ON Orders TO QueryRole;
D. GRANT SELECT ON Orders TO QueryRole WITH GRANT OPTION;
E. GRANT DBA TO QueryRole WITH ADMIN OPTION;

10. When creating a user using Enterprise Manager instead of the CREATE USER
statement, which additional privileges are granted to the user? (Choose the
best answer.)
A. SELECT_CATALOG_ROLE
B. SYSDBA
C. CONNECT
D. RESOURCE
E. DBA

Answers
1. B and D. You can query the DBA_PROFILES data dictionary view to determine
the settings of all profiles in the database, including the one George is supposed
to have assigned to him. The RESOURCE_LIMIT initialization parameter must
be set to TRUE for the concurrent sessions limit to be enforced, so you need
to verify this setting in the running instance and in the SPFILE. DBA_USER_
LIMITS, DBA_PROFILE_LIMITS, and V$LIMITS views do not exist.

2. B. When you create a user, you can specify at most one authentication
method. This SQL statement specified both EXTERNALLY and password
(BY $amP@ssw0rd) authentication at the same time, which would generate
an error when the command was executed.

3. A and F. If you have been granted a system privilege WITH ADMIN OPTION,
you can also grant the same privilege to others and specify the WITH ADMIN
OPTION. The WITH GRANT OPTION applies to object privileges and not
system privileges. If system privileges are revoked for a user to whom they
were granted WITH ADMIN OPTION, they will not be revoked for other
users to whom the revoke granted them; there are no cascading revokes for
system privileges. The DBA is a role and is not the only one that can grant
system privileges, and neither is the user SYS (the database owner), in that
anyone holding the DBA role can grant them, since the DBA role has system
privileges granted to it WITH ADMIN OPTION.

4. E. A user cannot himself change his active profile. Only the DBA can modify
a user’s profile or the profile limits.

5. A. If you do not specify a value for a limit in your profile, it will automatically
be assigned the value of DEFAULT. This means that Oracle will enforce whatever
value exists for the limit in the DEFAULT profile.

6. D. The currently defined database default temporary tablespace will be assigned
to the user if you do not specify a TEMPORARY TABLESPACE for the user. If
no database default temporary tablespace is defined, the user will be assigned
SYSTEM as the temporary tablespace.

7. E. Anthony, like any new user who has been configured with password
authentication, has the ability to change his password at any time. No other
changes to the user account are allowed to be performed by the user himself.

8. B and D. Benjamin can query your TempOrders table only if he is a DBA, who
automatically has the SELECT ANY TABLE privilege, or if Benjamin has been
granted the SELECT ANY TABLE privilege by the DBA. Another user to whom
you only granted the SELECT privilege could not grant it to Benjamin unless
you specified the WITH GRANT OPTION. Granting the UPDATE privilege on
the table does not automatically grant the SELECT privilege.

9. D. It is not possible to grant object privileges to roles WITH GRANT OPTION,
so this statement will fail. All other statements will succeed, assuming you
have the privileges required to perform the operation.

10. C. Using Enterprise Manager to create a user will automatically grant the user
the CONNECT role, which includes the CREATE SESSION privilege, so the
user is able to connect to the instance right away. This role also includes the
privileges to create tables, views, synonyms, sequences, and other database
objects, which may or may not be desired for all users.