Oracle Cheatsheet (10g and 11g)

This is a quick and dirty cheatsheet on Oracle 10g and 11g, below will contain most of the information you require to administer Oracle from a DBA point of view, I plan to update this section to include 12c.

Controlling Oracle

Oracle Stages
Startup (nomount) Oracle first reads the parameter file (pfile or spfile) and obtains all memory parameters in order to configure the SGA, memory allocatations take place and the necessary background processes are started. Remember the Memory allocation with the background processes is called the INSTANCE.
Mount At this stage Oracle opens and reads the controlfile and obtains the location of the datafiles but it does not open them.
Open The last stage is to open the datafiles (also called the DATABASE) for reading and writing, Oracle makes sure that the datafiles are consistent.

Oracle Startup
Nomount Mode startup nomount;

Note: The INSTANCE is born, memory allocated and background processes started but the controlfile has not been read and the datafiles are not open for reading or writing
Mount Mode

startup mount;

Note: The controlfile has been read at this stage but the datafiles are not open for reading or writing.

Read Only Mode

startup open read only

Note: the database files are open for reading only

Open Mode startup
startup open

Note: database files will be open for reading and writing, this is the normal mode of operation.

Force mode

startup force;

Note: this performs a 'shutdown abort' followed by a 'startup'

Restricted Mode

startup restrict;

# To change into restricted mode
alter system enable restricted session;
alter system disable restricted session;

Note: Users with restricted access can access the system only (normally DBA's)

Alter operation mode

# You must be in mount mode to alter the database, if not then shutdown the database first

alter database open;
alter database open read only;
alter database restricted;

Display operation mode

# Display instance state in nomount mode v$database is unavailable.
# MODES:
#   started (nomount mode)
#   mounted (mount mode)
#   open (open mode)

select status from v$instance;

# Obtain the database operation mode, the database must be in mounted or open mode to access v$database
# MODES:
#   mounted (mount mode)
#   read write (open mode)
#   read only (open mode)

select open_mode from v$database;

# Is restricted session enabled
select logins from v$instance;


Oracle Shutdown
Normal

No new connections
Will wait until all users have disconnected

Note: you could be waiting a long time, not normally used

Transactional

No new connections or transactions
Once all transactions have finished disconnect the client

Note: again you could be waiting a long time

Immediate No new connections
Uncommitted transactins will be rolled back then disconnect the client

Note: normal shutdown command used
Abort

No new connections
Disconnect client immediately (no rolling back any transactions)

Note: last resort shutdown command, a automatic recovery will take place when you start the database

Shutdown Commands
Shutdown commands

shutdown normal;
shutdown transactional;
shutdown immediate;
shutdown abort;

startup force;

Note: 'startup force' will run a 'shutdown abort' immediately followed by a 'startup'

Display if shutdown is in progress select shutdown_pending from v$instance;

Restricted and Quiesce Modes
Restricted

In this mode any users without the restricted privilege will not be allowed to connect to the database, however any users that are still connected will be allowed to use any DML/DDL.

Note: make sure all users are disconnected (need to kill their sessions) before changing the mode into restricted.

Quiesce

In this mode all users transactions are allowed to complete, once completed the user is unable to perform any DML/DDL commands (their sessions appear to freeze) but remain connected to the database. Users will be allowed to login but the session will again appear to freeze.

DBA's can perform any DML/DDL as normal, their sessions are unaffected, this also applies to users with the restricted session privilege.

Useful Commands
Restricted

alter system enable restricted session;
alter system disable restricted session;

select logins from v$instance;

Grant restricted privilege grant restricted session to <user>;
Quiesce alter system quiesce restricted;
alter system unquiesce;

select active_state from v$instance;

Database Basic Information
Display Parameter file select name, value from v$parameter where name = 'spfile';
show parameter spfile;
Parameter settings select name, value, isdefault, isses_modifiable, issys_modifiable from v$parameter;
Instance state select status from v$instance;
Database operation mode select open_mode from v$database;
Shutdown pending select shutdown_pending from v$instance;
Restricted Session Mode select logins from v$instance;
Quiesce Mode select active_state from v$instance;
Oracle version select * from v$version;
select * from product_component_version;
Log Mode

select log_mode from v$database;
archive log list;

License info select * from v$license;
Database options select * from v$option;
Memory Info show sga
select * from v$sga;
select * from v$sgainfo;
select * from v$ssgastat;
Display controlfiles select * from v$controlfile;
select * from v$controlfile_record_section;
Display Oracle processes select * from v$bgprocess;
Log file locations # display background (alert.log destination), core and user destinations
show parameter dump_dest;

System Files, Data Files, Tablespaces

Oracle Operating System Files
Parameter File These files tells Oracle were to find the control files, also they detail how big the memory area will be, etc. A parameter file can be either in binary (known as spfile) or a text file (known as pfile)
Data Files These hold the tables, indexes and all other segments
Temp Files Used for disk-based sorting and temporary storage
Redo Log Files Our transaction logs
Undo log files Allows a user to rollback a transaction and provides read consistency.
Archive Log Files Redo log files which have been archived
Control File

Details the location of data and log files and other relevant information about their state, other information include but not all

  • name of the database
  • names, location and size of the database and redo files
  • information regarding backups and recovery information
  • keeps all files in sync
Password File Used to authenticate users logging in into the database.
Log files alert.log contains database changes and events including startup information.
trace files Are debugging files.

Parameter file commands
create pfile using a spfile create pfile='c:\oracle\pfile\initD10.ora' from spfile;
startup db using pfile startup pfile='c:\oracle\pfile\initD10.ora';
create spfile using a pfile

create spfile from pfile;

Display spfile location show parameter spfile
Display the parameter file in use select name, value from v$parameter where name = 'spfile';
show parameter spfile;

Data File Contains
Segments are database objects, a table, a index, rollback segments. Every object that consumes space is a segment. Segments themselves consist of one or more extents.
Extents are a contiguous allocation of space in a file. Extents, in turn, consist of data blocks
Blocks

are the smallest unit of space allocation in Oracle. Blocks normally are 2KB, 4KB, 8KB, 16KB or 32KB in size but can be larger.

  • 2KB or 4KB - online transaction processing (OLTP) database would benefit from a small block size
  • 8KB - Most databases would be OK to use the default size
  • 16KB or 32KB - data warehouses (OLAP), media database would benefit from a larger block size
Data Block Contains
Header contains information regarding the type of block (a table block, index block, etc), transaction information regarding active and past transactions on the block and the address (location) of the block on the disk
Table Directory contains information about the tables that store rows in this block
Row Directory contains information describing the rows that are to be found on the block. This is an array of pointers to where the rows are to be found in the data portion of the block.
Block overhead The three above pieces are know as the Block Overhead and are used by Oracle to manage the block itself.
Free space available space within the block
Data data within the block
Datafile Commands
Resizing alter database datafile 'c:\oracle\test.dbf' resize 3G;
Offlining

alter database datafile 'c:\oracle\test.dbf' offline;

Note: you must offline the tablespace first

Onlining alter database datafile 'c:\oracle\test.dbf' online;
Renaming alter database rename file 'c:\oracle\test.dbf' to 'c:\oracle\test99.dbf';
Autoexend alter database datafile 'c:\oracle\test.dbf' autoextend on;
alter database datafile 'c:\oracle\test.dbf' autoextend off;

select file_name, autoextensible from dba_data_files;
Useful Data File Views
DBA_DATA_FILES describes database files

Tablespace Architecture
Tablespace Architecture
  • A database is made up of one or more tablespaces
  • A tablespace is made up of one or more data files, a tablespace contains segments
  • A segment (table, index, etc) is made up of one or more extents. A segment exists in a tablespace but may have data in many data files within a tablespace.
  • An extent is a continuous set of blocks on a disk. An extent is in a single tablespace and is always in a single file within that tablespace.
  • A block is the smallest unit of allocation in the database. A block is the smallest unit of i/o used by the database.
Tablespace Types
Bigfile tablespaces will have only one file which can range from 8-128 terabytes.
Smallfile tablespaces (default) can have multiple files but the files are smaller than a bigfile tablespace.
Temporary tablespaces contain data that only persists for the duration a users session, used for sorting
Permanent tablespaces any tablespace that is not temporary one.
Undo tablespaces Oracle uses this to rollback or undo changes to the db.
Read-only no write operations are allowed.
Managing Tablespaces
Locally (default)

Extents are the basic unit of a tablespace and are managed in bitmaps that are kept within the data file header for all the blocks within that data file. For example, if a tablespace is made up of 128KB extents, each 128KB extent is represented by a bit in the extent bitmap for this file, the bitmap values indicate if the extent is used or free. The bitmap is updated when the extent changes there is no updating on any data dictionary tables thus increasing performance.

Extents are tracked via bitmaps not using recursive SQL which means a performance improvement.

Locally managed tablespaces cannot be converted into a dictionary managed one. The benefits of using a local managed tablespace

  • relieves contention on the system tablespace
  • free extents are not managed by the data dictionary
  • no need to specify storage parameters
Dictionary Managed

The extent allocation is managed by the data dictionary and thus updating the extent information requires that you access the data dictionary, on heavy used systems this can cause a performance drop.

extents are tracked via FET$ and UET$ using recursive SQL.

Dictionary managed tablespaces can be converted to a locally managed one.

Tablespace Extent Management
Autoallocate (default)

This means the extent will vary in size, the first extent starts at 64k and progressively increased to 64MB by the database. The database automatically decides what size the new extent will be based on segment growth patterns.

Autoallocate is useful if you aren't sure about growth rate of an object and you let oracle decide.

Uniform

Create the extents the same size by specifying the size when create the tablespace.

This is default for temporary tablespace but not available for undo tablespaces.

Be careful with uniform as it can waste space, use this option you are know what the growth rate of the objects are going to be.

Tablespace Space Management
Manual Oracle manages the free space in the data blocks by using free lists and a pair of storage parameters PCTFREE and PCTUSED. When the block reaches the PCTUSED percentage the block is then removed from the freelist, when the block falls below the PCTFREE threshold the block is then placed back on the freelist. Oracle has to perform a lot of hard work maintaining these lists, a slow down in performance can occur when you are making lots of changes to the blocks as Oracle needs to keep checking the block thresholds.
Automatic (default)

Oracle does not use freelist when using automatic mode, Instead oracle uses bitmaps. A bitmap which is contained in a bitmap block, indicates whether free space in a data block is below 25%, between 25%-50%, between 50%-75% or above 75%. For an index block the bitmaps can tell you whether the blocks are empty or formatted. Bitmaps do use additional space but this is less than 1% for most large objects.

The performance gain from using automatic segment management can be quite striking.

Tablespace Commands
Creating create tablespace test datafile 'c:\oracle\test.dbf' size 2G;
create tablespace test datafile 'c:\oracle\test.dbf' size 2G extent management local uniform size 1M maxsize unlimited;
create bigfile tablespace test datafile 'c:\oracle\bigfile.dbf' 2G;
Creating non-standard block size create tablespace test datafile 'c:\oracle\test.dbf' size 2G blocksize 8K;
Removing

drop tablespace test;
drop tablespace test including contents and datafiles; (removes the contents and the physical data files)

Modifying

alter tablespace test rename to test99;
alter tablespace test [offline|online];
alter tablespace test [readonly|read write];
alter tablespace test [begin backup | end backup];

Note: use v$backup to see tablespace is in backup mode (see below)

Adding data files alter tablespace test add datafile 'c:\oracle\test02.dbf' 2G;
Dropping data files alter tablespace test drop datafile 'c:\oracle\test02.dbf';
Autoextending See Datafile commands below
Rename a data file alter tablespace test rename datafile 'c:\oracle\test.dbf' to 'c:\oracle\test99.dbf';
Tablespace management create tablespace test datafile 'c:\oracle\test.dbf' size 2G extent management manual;
Extent management create tablespace test datafile 'c:\oracle\test.dbf' size 2G uniform size 1M maxsize unlimited;
Segment Space management create tablespace test datafile 'c:\oracle\test.dbf' size 2G segment space management manual;
Display default tablespace select property_value from database_properties where property_name = 'DEFAULT_PERMANENT_TABLESPACE';
Set default tablespace alter database default tablespace users;
Display default tablespace type select property_value from database_properties where property_name = 'DEFAULT_TBS_TYPE';
Set default tablespace type alter database set default bigfile tablespace;
alter database set default smallfile tablespace;
Get properties of an existing tablespace set long 1000000
select DBMS_METADATA.GET_DDL('TABLESPACE','USERS') from dual;
Free Space select tablespace_name, round(sum(bytes/1024/1024),1) "FREE MB" from dba_free_space group by tablespace_name;
Display backup mode select tablespace_name, b.status from dba_data_files a, v$backup b where a.file_id = b.file#;
Useful Tablespace Views
DBA_TABLESPACES describes all tablespaces in the database
DBA_DATA_FILES describes database files
DBA_TABLESPACE_GROUPS describes all tablespace groups in the database
DBA_SEGMENTS describes the storage allocated for all segments in the database
DBA_FREE_SPACE describes the free extents in all tablespaces in the database
V$TABLESPACE displays tablespace information from the control file
V$BACKUP displays the backup status of all online datafiles
DATABASE_PROPERTIES lists Permanent database properties

Temporary Tablespace commands
Creating non temp group create temporary tablespace temp tempfile 'c:\oracle\temp.dbf' size 2G autoextend on;
Creating temp group create temporary tablespace temp tempfile 'c:\oracle\temp.dbf' size 2G tablespace group '';
Adding to temp group

alter tablespace temp02 tablespace group tempgrp;

Note: if no group exists oracle will create it

Removing from temp group alter tablespace temp02 tablespace group '';
Displaying temp groups select group_name, tablespace_name from dba_tablespace_groups;
Make user use temp group alter user vallep temporary tablespace tempgrp;
Display default temp tbs

select property_value from database_properties where property_name = 'DEFAULT_TEMPORARY_TABLESPACE';
select property_value from database_properties where property_name = 'DEFAULT_TEMP_TABLESPACE';

set default temp tbs alter database default temporary tablespace temp02;
Display free temp space select tablespace_name, sum(bytes_used), sum(bytes_free) from v$temp_space_header group by tablespace_name;
Who is using temp segments SELECT b.tablespace,
  ROUND(((b.blocks*p.value)/1024/1024),2)||'M' "SIZE",
  a.sid||','||a.serial# SID_SERIAL,
  a.username,
  a.program
FROM sys.v_$session a,
  sys.v_$sort_usage b,
  sys.v_$parameter p
WHERE p.name = 'db_block_size'
  AND a.saddr = b.session_addr
ORDER BY b.tablespace, b.blocks;
Useful Temporary Views
DBA_TEMP_FILES describes database temporary files
DBA_TABLESPACE_GROUPS describes all tablespace groups in the database
V$SORT_SEGMENT contains information about every sort segment in a given instance. The view is only updated when the tablespace is of the temporary type
V$TEMPSEG_USAGE describes temporary segment usage

ControlFiles
Useful Views
V$CONTROLFILE Lists the controlfiles
V$CONTROLFILE_RECORD_SECTION View the controlfile's record structure

Transactions Management, Locking and Concurrency

ACID Properties
Atomicity A transaction either happens completely, or none of it happens
Consistency A transaction takes the database from consistent state to the next
Isolation The effects of a transaction may not be visible to other transaction until the transaction has committed.
Durability Once the transaction is committed, it is permanent all changes are written to the redo log first then the data files.

Concurrency Problems
Dirty Reads Occurs when a transaction reads data that has been updated by an ongoing transaction but has not been committed permanently to the database, it is possible that the transaction may be rolled back.
Phantom Reads Are caused by the appearance of new data in between two database operations in a transaction.
Lost Updates Is caused by transactions trying to read data while it is being updated by other transaction.
Non-Repeatable Reads When a transaction finds data that it has read previously has been modified by some other transaction, you have a non-repeatable-read or fuzzy read. Basically when you read data at one time and its different when you read it again.

Isolation Levels
Serializable Then transaction will lock all the tables it is accessing to prevent other transactions updating data until it either rollbacks or commits
Repeatable Read A transaction that reads the data twice from a table at different points in time will find the same values each time. Both dirty reads and non-repeatable are avoided with this level of isolation.
Read uncommitted Allows a transaction to read another transaction's immediate value before it commits
Read committed Guarantees that the row data won't change while you're accessing a particular row in a table.

Oracle Locks
DML Locks Oracle uses row-level locks, this is to protect the row while its being changed, the lock will never block a reader of the same row. A table lock is also placed but this ensures that no DDL is used on the table.
DDL Locks When changing table attributes Oracle places a exclusive lock on the table to prevent any modifications to the rows. This lock is also used during DML transactions to make sure the table is not changed when changing or inserting data.
Latches Latches protect the memory structure with the SGA, they control the processes that access the memory area's.
Internal Locks Are used by oracle to protect access to structures such as data files, tablespaces and rollback segments.
Distributed Locks Are specialized locking mechanisms used in distributed systems.
Blocking Locks Occurs when a lock is placed on an object by a user to prevent other users accessing the same object.
DeadLocks Occurs when two sessions block each other while each waits for a resource that the other session is holding. Oracle always steps in to resolve the issue by killing one of the sessions, check the alert.log for deadlocks.
Useful Views
DBA_LOCK lists all locks or latches held in the database, and all outstanding requests for a lock or latch
DBA_WAITERS shows all the sessions that are waiting for a lock
DBA_BLOCKERS displays a session if it is not waiting for a locked object but is holding a lock on an object for which another session is waiting
V$LOCK This view lists the locks currently held by the Oracle Database and outstanding requests for a lock or latch
V$SESSION

This view lists session information for each current session


Oracle Transaction Steps
Transaction Steps
  1. User requests a connection to oracle
  2. A new dedicated server process is started for the user
  3. User executes a statement to insert data in to a table
  4. Oracle checks the users privileges, it first checks the library cache (cache hit) for the information and if not found retrieve it from disk.
  5. Check to see if the SQL statement has been parsed before (library cache) if it has then this is called a soft parse, otherwise the code has to be compiled a hard parse.
  6. Oracle creates a private SQL area in the users session's PGA
  7. Oracle checks to see if the data is in the buffer cache, otherwise perform a read from the data file
  8. Oracle will then apply row-level locks where needed to prevent others changing the row (select statements are still allowed on the row)
  9. Oracle then writes the change vectors to the redo log buffer
  10. Oracle then modifies the row in the data buffer cache
  11. The user commits the transaction making it permanent, the row-level locks are released
  12. The log writer process immediately writes out the changed data in the redo log buffers to the online redo log files, in other words the change is now recoverable.
  13. Oracle informs the user process that the transaction was completed successfully
  14. It may be sometime before the data buffer cache writes out the change to the data files.

Undo and Transaction Management

Redo Log Group States
Current log group that is being actively being written too.
Active the files in the log group are required for instance recovery
Inactive the files in the log group are not required for instance recovery and can be over written
Unused log group has never been written too, a new group.
Redo Log File States
Invalid the file is corrupt or missing
Stale the log file is new and never been used
Deleted the log file is no longer being used
<blank> the log file is currently being used
Redo Commands
Configuration
Creating new log group alter database add logfile group 4 ('c:\oracle\redo3a.log','c:\oracle\redo3b.log') size 10M;
Adding new log file to existing group alter database add logfile member 'c:\oracle\redo3c.log' to group3;
Renaming log file in existing group

shutdown database
rename file
startup database in mount mode
alter database rename file 'old name' to'new name'
open database
backup controlfile

Drop log group alter database drop logfile group 3;
Drop log file from existing group alter database drop logfile member 'c:\oracle\redoc.log'
Maintaining
Clearing Log groups

alter database clear logfile group 3;
alter database clear unarchived logfile group 3;

Note: used the unarchived option when a loggroup has not ben archived

Logswitch and Checkpointing

alter system checkpoint;

alter system switch logfile;
alter system archive log current;
alter system archive log all;

# Difference between them are
switch logfile - will switch logfile and return prompt immediately, archiving will take place in the background
log current - will switch logfile and return prompt only when logfile has been successfully archived
log all - will only archiving full log files

Note: I have discussed checkpoints

Display the redo usage select le.leseq "Current log sequence No",
  100*cp.cpodr_bno/le.lesiz "Percent Full",
  cp.cpodr_bno "Current Block No",
  le.lesiz "Size of Log in Blocks"
from x$kcccp cp, x$kccle le
where le.leseq =CP.cpodr_seq
and bitand(le.leflg,24) = 8
/
Useful Views
V$LOG displays log file information from the control file.
V$LOGFILE contains information about redo log files.

Archive Redo Logs
Configuration
Enabling

alter system set log_archive_dest_1 = 'location=c:\oracle\archive' scope=spfile;
alter system set log_archive_format = 'arch_%d_%t_%r_%s.log' scope=spfile;

shutdown database
startup database in mount mode
alter database archivelog;
startup database in open mode

Archive format options
%r - resetlogs ID (required parameter)
%s - log sequence number (required parameter)
%t - thread number (required parameter)
%d - database ID (not required)

Disabling alter database noarchivelog;
Displaying archive log list;
select name, log_mode from v$database;
select archiver from v$instance;
Maintainance
Display system parameters show parameter log_archive_dest
show parameter log_archive_format
show parameter log_archive_min_succeed_dest
Useful Views
V$ARCHIVED_LOG Display the archived log files
V$INSTANCE Display if database is in archive mode
V$DATABASE Display if database is in archive mode

Undo Parameters
UNDO_MANAGEMENT (default manual)

This is the only mandatory parameter and can be set to either auto or manual.

UNDO_TABLESPACE
(default undo tablespace)

This specifies the tablespace to be used, of course the tablespace needs to be a undo tablespace. If you do not set this value oracle will automatically pick the one available. If no undo tablespace exists then oracle will use the system tablespace which is not a good idea (always create one).
UNDO_RETENTION
(seconds)

Once a transaction commits the undo data for that transaction stays in the undo tablespace until space is required in which case it will be over written.

Undo Commands
Undo System Management
Management alter system set undo_management=auto;
Setting alter system set undo_tablespace = 'undotbs02';
Retention alter system set undo_retention = 43200; (it's in seconds)
Undo Control
Creating create undo tablespace undotbs2 datafile 'c:\oracle\undo02.dbf' size 2G;
Removing drop undo tablespace undotbs02;

guarantee

alter tablespace undotbs02 retention guarantee;
alter tablespace undotbs02 retention noguarantee;
See current undo blocks

select begin_time, undotsn, undoblks, activeblks, unexpiredblks, expiredblks from v$undostat;

Contains snapshots of v$undostat (use obtain the oldest undo available)

select begin_time, undotsn, undoblks, activeblks, unexpiredblks, expiredblks from dba_hist_undostat;

NOTE: If your current undo_retention period is 6 days then the oldest undo data in dba_hist_undo should be 6 days old.

Useful Views
DBA_ROLLBACK_SEGS describes rollback segments
DBA_TABLESPACES describes all tablespaces in the database
DBA_UNDO_EXTENTS describes the extents comprising the segments in all undo tablespaces in the database
DBA_HIST_UNDOSTAT displays the history of histograms of statistical data to show how well the system is working. The available statistics include undo space consumption, transaction concurrency, and length of queries executed in the instance. This view contains snapshots of V$UNDOSTAT.
V$UNDOSTAT displays a histogram of statistical data to show how well the system is working. The available statistics include undo space consumption, transaction concurrency, and length of queries executed in the instance. You can use this view to estimate the amount of undo space required for the current workload. Oracle uses this view to tune undo usage in the system. The view returns null values if the system is in manual undo management mode.
V$ROLLNAME lists the names of all online rollback segments. It can only be accessed when the database is open.
V$ROLLSTAT contains rollback segment statistics
V$TRANSACTION lists the active transactions in the system

Flashback Recovery Area
Monitoring

select * from v$recovery_file_dest;

Note: this details space_used, space_limit, space_reclaimable, # of files

What is using the Flashback recovery area select * from v$flash_recovery_area_usage;
Backing up flashback area

rman> backup recovery area;
Note: includes backup sets, datafile and archive, controlfile excludes: flashback log, current controlfile, online redo logs

rman> backup recovery files;
Note: includes all files whether or not they are in the flash recovery area

Restore Points
Not Guaranteed
create create restore point large_update;
remove drop restore point large_update;
Guaranteed
create guaranteed restore point create restore point test_guarantee guarantee flashback database;
remove guaranteed restore point drop restore point test_guarantee;
Other Operations
Using a restore point flashback database to restore point large_update;
flashback table test to restore point table_update;
Displaying restore points select name, scn, storage_size, time, guarantee_flashback_database from v$restore_point;
Flashback databse running

select flashback_on from v$database;

Note: you should get a restore point only reply if using restore points


Flashback Levels
row level flashback query, flashback versions query, flashback transaction query
table level flashback table, flashback drop
database level flashback database
Flashback Description
Flashback query retrieves data from a past point in time (uses UNDO data)
Flashback versions query shows you different versions of data rows, plus start and end times of a particular transaction that created that row (uses UNDO data)
Flashback transaction query lets you retrieve historical data for a given transaction and the SQL code to undo the transaction (uses UNDO data)
Flashback table recovers a table to its state at a past point in time, without having to perform a point in time recovery (uses UNDO data)
Flashback database restore the whole database back to a point in time (uses Flashback logs and Recyclebin)
Flashback drop allows you to reverse the effects of a drop table statement, without resorting to a point-in-time recovery (uses Flashback logs and Recyclebin)
Flashback Query
Privilege grant flashback on table_test to pvalle;
grant flashback on any table to pvalle;
Flashback query (time)

select * from employees as of timestamp
to_timestamp('03-12-2007 08:00:00', 'DD-MM-YYYY HH:MI:SS')
where last_name = valle;

select employee_id, name from hr.employee as of timestamp (systimestamp - interval '15' minute);

Flashback query (SCN)

select * from employees as of scn 4542;

Note: using a scn will put you with 3 secs if you need to be dead accurate use timestamps instead.

Take the whole session back in time

grant execute on dbms_flashback to test01;

execute dbms_flashback.enable_at_time(to_timestamp('03-12-2007 08:00:00', 'DD-MM-YYYY HH:MI:SS'));

execute dbms_flashback.disable;

Reinserting

insert into employees
select * from employees as of timestamp
to_timestamp('03-12-2007 08:00:00', 'DD-MM-YYYY HH:MI:SS')
where last_name = valle;

insert into employees select * from employees as of scn = 4542;

List the flashback entries select * from flashback_transaction_query;
Obtain a time from an SCN select scn_to_timestamp(1408640) as ts from dual;
Obtain SCN from time point select timestamp_to_scn(to_timestamp('03-12-2007 08:00:00', 'DD-MM-YYYY HH:MI:SS')) as scn from dual;
What is in the undo tablespace

select begin_time, end_time, tuned_undoretention from v$undostat;

Note: the time is in seconds

Flashback Version Query
Useful Columns
  • VERSIONS_STARTTIME - start timestamp of version
  • VERSIONS_STARTSCN - start SCN of version
  • VERSIONS_ENDTIME - end timestamp of version
  • VERSIONS_ENDSCN - end SCN of version
  • VERSIONS_XID - transaction ID of version
  • VERSIONS_OPERATION - DML operation of version
Flashback version query (time)

select versions_xid as xid, versions_startscn as start_scn, versions_endscn as end_scn,   versions_operation as operation, empname
from employees
  versions between timestamp minvalue and maxvalue
order by versions_startscn;

Flashback version query (SCN) select versions_xid as xid, versions_startscn as start_scn, versions_endscn as end_scn,   versions_operation as operation, empname
from employees
  versions between scn minvalue and maxvalue
where emp_id = 863;
Obtain a time from an SCN select scn_to_timestamp(1408640) as ts from dual;
Obtain SCN from time point select timestamp_to_scn(to_timestamp('03-12-2007 08:00:00', 'DD-MM-YYYY HH:MI:SS')) as scn from dual;
Flashback Transaction Query
Useful Columns
  • start_scn and start_timestamp - identify when a certain was created
  • commit_scn and commit_timestamp - tell you when a certain row was committed
  • xid_row_id and undo_change# - identify the row, transaction and change numbers
  • operation - tells you what sort of operation occurred insert, delete or update.
  • logon_user, table_name and table_owner - username, table name and schema name
  • undo_sql - the exact SQL code to undo the change
Privilege grant select any transaction to pvalle;
Supplemental logging alter database add supplemental log data;
Display undo segments select operation, undo_sql, table_name from flashback_transaction_query;
Flashback transaction query

select operation, undo_sql, table_name
from flashback_transaction_query
where start_timestamp >= to_timestamp ('04-12-2007 05:00:00', 'DD-MM-YYYY HH:MI:SS')
and commit_timestamp <= to_timestamp ('04-12-2007 08:00:00', 'DD-MM-YYYY HH:MI:SS')
and table_owner='VALLEP';

Note: this will give you the SQL to reserver the change that was applied to the database,just cut and paste to use.

Obtain a time from an SCN select scn_to_timestamp(1408640) as ts from dual;
Obtain SCN from time point select timestamp_to_scn(to_timestamp('03-12-2007 08:00:00', 'DD-MM-YYYY HH:MI:SS')) as scn from dual;
Flashback Table
Privilege grant flashback on table_test to pvalle;
grant flashback on any table to pvalle;
Enable row movement alter table test enable row movement;
Display row movement select table_name, row_movement from user_tables;
Flashback table (SCN) flashback table test to scn 4587309871;
Flashback table (time)

flashback table employees to timestamp to_timestamp
('04-12-2007 05:00:00', 'DD-MM-YYYY HH:MI:SS')

flashback table employees to timestamp (systimestamp - interval '15' minute);

flashback table employess to timestamp (sysdate - 1);

flashback table employees, depts to timestamp (sysdate - 1);

Enable triggers

flashback table employees to timestamp (sysdate -1) enable triggers;

Note: Oracle disables triggers by default when falshing back a table

Flashback Drop
Recover flashback table <table_name> to before drop
Recover and rename

flashback table <table_name> to before drop rename to <new name>;

Note: use if table name already exists

Recover same name table flashback table 'BIN$hfkjdshfkhs' to before drop;
List recycle bin select object_name, original_name, type from user_recyclebin;
select object_name, original_name, type from dba_recyclebin;
select * from recyclebin; (shows only current user info)
show recyclebin;
drop table completely

drop table <table_name> purge;

Note: table will not be in recyclebin

drop table from r/bin

purge table <table_name>

Note: table will be gone from recyclebin

truncate table

truncate table

Note: table will not be in the recyclebin

drop user

drop user test cascade

Note: will not store anything in the recyclebin

purge recyclebins purge recyclebin; (purge user recyclebin)
purge dba_recyclebin;(purges all recyclebins)
purge tablespace test user test03; (purge test03 from tablespace test)
List dropped table contents

select * from "BIN$NwM/FEjuSUORrgxHUPR3WA==$0";

Note: the double quotes

Naming Convention BIN$globalUID$version
Flashback Database
Recover flashback table <table_name> to before drop
Recover and rename

flashback table <table_name> to before drop rename to <new name>;

Note: use if table name already exists

Recover same name table flashback table 'BIN$hfkjdshfkhs' to before drop;
List recycle bin select object_name, original_name, type from user_recyclebin;
select object_name, original_name, type from dba_recyclebin;
select * from recyclebin; (shows only current user info)
show recyclebin;
drop table completely

drop table <table_name> purge;

Note: table will not be in recyclebin

drop table from r/bin

purge table <table_name>

Note: table will be gone from recyclebin

truncate table

truncate table

Note: table will not be in the recyclebin

drop user

drop user test cascade

Note: will not store anything in the recyclebin

purge recyclebins purge recyclebin; (purge user recyclebin)
purge dba_recyclebin;(purges all recyclebins)
purge tablespace test user test03; (purge test03 from tablespace test)
List dropped table contents

select * from "BIN$NwM/FEjuSUORrgxHUPR3WA==$0";

Note: the double quotes

Naming Convention BIN$globalUID$version

Resumable Database Options
Queries they can always be resumed after the temporary tablespace has run out of space.
DML Operations insert, delete and update can all be resumed
DDL Operations index operations involving creating, rebuilding and altering are resumable as are create table as select operations
import and export operations SQL loader jobs are resumable but to must use the resumable parameter in the SQL loader job
Resumable Commands
Privilege

grant resumable to vallep;

grant execute on dbms_resumable to vallep;

Who has privilege select grantee, privilege from dba_sys_privs where privilege='RESUMABLE';
Who has set resumable mode select user_id, session_id, status, timeout, name from dba_resumable;
Who is in resumable mode waiting for space

select user_id, session_id, name, timeout, start_time, suspend_time from dba_resumable;

select username, event from v$session where event like '%sus%';

Resumable space across entire database

resumable_timeout=7200;

Note: default is 0, time is in seconds

Resumable space in session alter session enable resumable;
Resumable space in session with timeout

alter session enable resumable timeout 18000;

execute dbms_resumable.set_timeout(18000);

Note: time is in seconds

Resumable space in session and adding a name alter session enable resumable name 'pauls_resumable';
Display resumable space mode options

select dbms_resumable.get_timeout() from dual;

Disable resumable space mode alter session disable resumable;
Useful Views
DBA_SYS_PRIVS describes system privileges granted to users and roles.
DBA_RESUMABLE lists all resumable statements executed in the system.
V$SESSION lists session information for each current session

Schema and User Management

System Accounts
SYS Owns all internal tables
SYSTEM Has additional tables and views
SYSMAN Use by OEM to monitor and gather performance stats, which are stored in the sysaux tablespace
DBSNMP Same as sys but for the OEM, owns all internal tables in the sysaux tablespace.

User Commands
Creating

create user vallep identified by password;
create user vallep identified by password default tablespace users temporary tablespace temp quota 100m on users;

Remove

drop user vallep;
drop user vallep cascade;

Note: the cascade option will remove all the users objects as well.

Alter alter user vallep idenitfied by newpassword;
alter user vallep quota 200m on users;
Password options

alter user vallep identified by password;
alter user vallep identified externally;
alter user vallep identified globally as extname;

Note:
identified by - the password will be kept in the data dicitonary
identified externally - authenication will be performed by the O/S
idenitified globally as extname - authenication will be performed by external app i.e radius

a user is only allowed to change is his/her password

Expire password alter user vallep password expire;
Lock/unlock alter user vallep account lock;
alter user vallep account unlock;
Connecting

grant create session to vallep;

Note: this allows the user to connect to the database

Revoke access revoke create session from vallep;
Quota alter user vallep quota 100m on users;
alter user vallep quota unlimited on users;
grant unlimited tablespace to vallep;
Kill a users session select username, sid, serial# from v$session;
alter system kill session '<session_id>,<session-serial>';
User connection type
(decicated/shared)
select username, program, server from v$session;
Useful Views
DBA_USERS describes all users of the database
DBA_TS_QUOTAS describes tablespace quotas for all users
V$SESSION lists session information for each current session

Profiles Resource Options
connect_time limits session to number of minutes
cpu_per_call limits cpu time by any single database call
cpu_per_session limit cpu by session
idle_time limit session to idle time, allows user to rollback or commit before logging off
logical_reads_per_call caps the amount of work by any single database call
logical_reads_per_session caps the amount of work by any session
private_sga limits memory when using shared servers
sessions_per_user limits the number of sessions a user can have
composite_limit calculated by cpu_per_session, logical_reads_per_session, connection_time and private_sga
Profile Security Features
failed_login_attemps number of times a user can enter the wrong password before the account is locked
password_lock_time if the above is breached lock password for this number of days
password_life_time number of days a password can remain in force
password_grace_time number of days user is notified but is used in above value
password_reuse_time maximum # of days before a password can be reused
password_reuse_max minimum # of different passwords before password can be reused
password_verify_function allows the use of a function to be used to verify a password
Profile Commands
Enable resource limits alter system set resource_limit = true scope = both;
Disable resource limits alter system set resource_limit = false scope = both;
Creating create profile user_profile limit sessions_per_user 5;
Remove

drop profile user_profile cascade;

Note: any users using the dropped profile will be automatically assigned the default profile

Setting a limit alter profile user_profile limit idle_time 30;
Displaying current resource limits select * from user_resource_limits;
Displaying current password limits select * from user_password_limits;
Displaying profile select * from dba_profiles where profile = 'USER_PROFILE';
Assign a profile alter user vallep profile user_profile;
Useful Views
USER_RESOURCE_LIMITS displays the resource limits for the current user.
USER_PASSWORD_LIMITS describes the password profile parameters that are assigned to the user.
DBA_PROFILES displays all profiles and their limits

System Privileges
Granting

grant create session to vallep;
grant create tablespace to vallep;
grant create user, alter user, drop user to vallep;

Revoking revoke create session from vallep;
revoke create tablespace from vallep;
Allow user to also grant this privilege

grant create session to vallep with admin option;

Note: now vallep can also grant this privilege

Useful Views
SYSTEM_PRIVILEGE_MAP table to list all system privileges
DBA_USERS provides information about users
DBA_SYS_PRIVS see who has system privileges

Powerful System Privileges
SYSOPER

perform startup and shutdown operations
mount/dismount and open/close the database
use alter database commands (BACKUP, ARCHIVE, LOG AND RECOVER)
perform archiving and recovery operations
create a spfile

SYSDBA

All the SYSOPER privileges

use the create database command
all system privileges with admin option


Object Privileges
table select, insert, update, delete, alter, debug, index and references
views select, insert, update, delete, debug and references
sequences select and alter
Functions, procedures, packages debug and execute
Commands
Grant grant select, insert, delete, update on employees to vallep;
grant select on employees to public;

grant update (product_id) on products to vallep;
Revoke revoke select, insert, delete, update on employees from vallep;
revoke select on employees from public;

revoke update (product_id) on products from vallep;
Allow user to also grant this privilege grant select on employees to vallep with grant option;
Useful Views
DBA_TAB_PRIVS show users table privileges
DBA_COL_PRIVS show users columns privileges

Roles
creating

create role test_role identified by <password>;

Note: the password is optional, you can also use externally or globally authentication

removing drop role test_role;
adding privileges to role grant select on HR.employees to test_role;
grant exp_full_database to test_role;
removing privileges from role revoke select on HR.employees from test_role;
revoke exp_full_database from test_role;
adding a role to a role

grant dba to test_role;

Note: the dba is a very powerful role be careful giving this out to anyone

granting a role to a user grant test_role to valle;
grant test_role to vallep with admin option;
revoking a role from a user revoke test_role from vallep;
list roles/privileges select * from session_roles;
select * from session_privs;
setting session role set role test_role identified by <password>;
set default alter user vallep default role test_role
Useful Views
DBA_ROLES list all the roles
DBA_ROLE_PRIVS

lists the users granted roles

Note: useful columns are with admin option, default role

ROLE_SYS_PRIVS lists the roles system privileges and what roles have other roles within them
ROLE_TAB_PRIVS lists the roles table privileges
ROLE_ROLE_PRIVS lists what other roles the role has (roles within roles)
SESSION_ROLES lists current role in use.
SESSION_PRIVS show privileges currently enabled for the user

Connectivity

Listener Registation
Dynamically register the default listener

1. Register the default listener to the instance

   # alter system set instance_name = P01;
   # alter system set service_names = P01;

Note: port 1521 is assumed, you do not need to update the listener.ora file

Dynamically register a non-default listener

1. Create the listener (use Net Manager)
2. Create the Net Service name (Use Net Configuration Assistant)
3. Register the service with the instance

   # alter system set local_listener = 'P01_1522';
   # alter system register;

Note: you need to update the listener.ora and tnsnames.ora files


Listener Commands
starting lsnrctl start
stopping lsnrctl stop
status lsnrctl status
Reloading configuration lsnrctl reload
Display Services lsnrctl services
Save the configuration lsnrctl save_config
Set tracing ON lsnrctl trace
Help lsnrctl help
Number of set/show commands

current_listener
displaymode
inbound_connection_timeout
log_status
log_file
log_directory
trc_level
trc_file
trc_directory
password     (only set is available)


Dispatchers and Shared Servers
Setup Dispatchers

# alter system set dispatchers="(protocol=TCP)(dispatchers=2)";
# alter system set dispatchers="(protocol=IPC)(dispatchers=2)";
# alter system set dispatchers="(protocol=TCP)(dispatchers=2)(pool=on)(tick=1)(connections=500)(sessions=1000)";

# alter system set max_dispatchers = 10;

pool - provides connection pooling
tick - number of 10 minute intervals of inactivity for a connection to be considered idle
connections - maximum number of concurrent sessions
sessions - maximum number of sessions per dispatcher
listener - address of listener to which PMON sends info to when listener is non-local and the local_listener is not set

Shared Server

# alter system set shared_servers = 5;
# alter system set shared_server_sessions = 2;
# alter system set max_shared_server = 20;

shared_servers - the system will initially start this many (default = 1)
shared_server_sessions - maximum number of shared server sessions
max_shared_server - shared servers will grow to this limit

Note: If at anytime you get ORA-00018 errors (Logging in or EM reports this error) this is because "shared_server_sessions" has been set too low

Circuits # alter system set circuits = 300;
Useful Views
V$DISPATCHER displays information about the dispatcher processes
V$DISPATCHER_CONFIG displays information about the dispatcher configurations and their attributes
V$DISPATCHER_RATE displays rate statistics for a number of activities performed by the dispatcher processes
V$QUEUE contains information on the shared server message queues
V$SHARED_SERVER contains information on the shared server processes
V$SHARED_SERVER_MONITOR contains information for tuning the shared server
V$CIRCUIT contains information about virtual circuits, which are user connections to the database through dispatchers and servers
V$SESSION lists session information for each current session
Useful SQL Code
List the dedicated server processes

select a.spid dedicated_server, b.process clientpid
from v$process a, v$session b
where a.addr = b.paddr
and b.audsid = userenv('sessionid');

Note: remove the last line for all dedicated processes

List the dispatchers Select * from v$dispatcher;
List the shared server processes

select count(*) "Shared Server processes"
from v$shared_server
where status != 'QUIT';

Display average wait time per request SELECT DECODE(TOTALQ, 0, 'No Requests',WAIT/TOTALQ || ' HUNDREDTHS OF SECONDS')
"AVERAGE WAIT TIME PER REQUESTS" FROM V$QUEUE WHERE TYPE = 'COMMON';

Display levels and maximum levels

select 'session count from v$session', count(*) from v$session
union
select 'session utilization from v$resource_limit', current_utilization
   from v$resource_limit where resource_name = 'sessions';

Backups and Recovery

Operational Management

Managing and Monitoring the Database