DBA Interview Questions With Answers Part1to12
DBA Interview Questions With Answers Part1to12
DBA Interview Questions With Answers Part1to12
If we are getting any issue regarding database while performing any activity we should
check alert log file in dump destination.. The four common error we find in alert.log are:
Deadlock Errors (ORA-00060), Oracle Internal errors, Backup and recovery errors, Snapshot too
old error (O1555)
What is PCT Free/PCT Used/PCT increase parameter in segment? What is growth factor?
PCT-FREE is a block storage it uses to mention how much space should be left in database block
for future updates (updating the records eg. previously name Smith after that we will update the
name as Smith Taylor). If mention PCTFREE as 10, oracle will adding the new rows to block up
to 90% it allows 10% for future updates.
If the PCT used was set to 60 this means if the data inside the block is 60 it is FULL and if the
data inside the block is 59 it is Empty.
This is the parameter which specify in percent that a block can only used for insert or come in
the free list(list of blocks in segment ready for insert operation) when used space in a block is
less than PCTUSED.
Suppose value of pctused is 40 and pctfree is 20 then data can be inserted till 80 of the block
directly. And suppose the used space is 60 and some one has perform a delete operation in a row
in the same block which brings the used space to 50 .Now one cannot insert any record in the
same block unless the used space comes down below 40 i.e. pctused.
The dump destination is the location where the trace files are located for all the Oracle process.
bdump-->Background processes + alert_SID.log file location
cdump--> Core Processes dump, udump--> User Processes dump, adump--> for ASM processes
These destinations contains useful information related to process failures.
UDUMP is specifying the user dump directory where all user error logs (trace files) will be
placed.
BDUMP is specifying the background dump directory where all database error logs (trace files)
will be placed.
CDUMP is specifying the core dump directory where all OS error logs (core dump files) will be
placed.
Default location is (ORACLE_BASE/admin/<SID>)
SQL>show parameters dump_dest;
It'll show you all the dump directories wherever it is currently located. You can change your
parameters in init.ora by creating spfile from pfile.
What will you do if in any condition you do not know how to troubleshoot the error at all
and there are no seniors or your co-workers around?
We need to find where in the compilation the error is occurring. We have to divide the code and
check for correctness of the code part-by-part. This is called debugging. Keep checking the code
until you find the code which is wrong.
Search forums for similar error codes or symptoms and make a plan then submit it to your
supervising DBA if you are not authorized to carry it out yourself.
I am getting error "No Communication channel" after changing the domain name? What is
the solution?
Here Question is not clear about Where the Oracle database is residing. If the Oracle Database is
resides on your local machine then the domain name must be updated in the tnsnames.ora file.
Change this file in ../Admin folder contained one. If you are accessing remote Database then
there are no changes required to your tnsnames.ora file only check with tnsping with the
database service name. Change the domain name in the sqlnet.ora file in
NAMES.DEFAULT_DOMAIN parameter
You have taken import of a table in a database. You have got the Integrity constraint
violation error. How you are going to resolve it.
If u wants to import the table just says constraints=n the movement table got imported then u
create constraint on that tables.
What is the most important action a DBA must perform after changing the database from
NOARCHIVELOG TO ARCHIVELOG?
First of all take an offline backup of whole database (including the (datafile controlfile and
redolog files). It is obvious that archive log process should be started by:
SQL>alter system Archivelog start;
Show one instance when you encountered an error in alert log and you overcome that
error. What actions you took to overcome that error.
Oracle writes error in alert log file. Depending upon the error corrective action needs to be
taken.
1) Deadlock Error: Take the trace file in user dump destination and analysis it for the error.
2) ORA-01555 Snapshot error: Check the query try to fine tune and check the undo size.
3) Unable to extent segment: Check the tablespace size and if require add space in the
tablespace by 'alter database datafile .... resize' or alter tablespace add datafile command.
Oracle Rollback Segments (Undo more recently) hold a copy of data before it was modified and
they work in a round-robin fashion. Writing and then eventually overwriting the entries as soon
as the changes are committed.
They are needed to provide read consistency (a consistent set of data at a point in time) or to
allow a process to abandon or rollback the changes or for database recovery.
User A opens a query to fetch every row from a billion row table. If User B updates and commits
the last row of the billion row table a Rollback entry will be created so User A can see the data as
it was before the update.
Other users are busily updating rows in the database and this in turn generates rollback – which
may eventually cause the entry needed for User A to be overwritten (after all User B did commit
the change – so it’s OK to overwrite the rollback segment). Maybe 15 minutes later the query is
still running and User A finally fetches the last row of the billion row table – but the rollback
entry is gone. He gets ORA-01555: Snapshot too old rollback segment too small
I have applied the following commands: Now what will happen, will the database will give
an error / it will work?
Shutdown abort;
Startup;
Definitely database will be start without error but all uncommitted data will be lost such as
killed all sessions, killed all transactions, and didn't write from the buffers because shutdown
abort directly shutdown instance without committing.
What is mutated trigger? In single user mode we got mutated error, as a DBA how you will
resolve it?
Mutated error will occur when same table access more than once in one state. If you are using
before in trigger block then replace it with after.
Explain Dual table. Is any data internally stored in dual Table. Lot of users is accessing
select sysdate from dual and they getting some millisecond differences. If we execute
SELECT SYSDATE FROM EMP; what error will we get. Why?
Dual is a system owned table created during database creation. Dual table consist of a single
column and a single row with value x. We will not get any error if we execute select sysdate from
scott.emp instead sysdate will be treated as a pseudo column and displays the value for all the
rows retrieved. For Example if there is 12 rows in emp table it will give result of date in 12 rows.
As an Oracle DBA what are the entire UNIX file you should be familiar with?
A database instance also known as server is a set of memory structures and background
processes that access a set of database files. It is possible for a single database to be accessed by
multiple instances (this is oracle parallel server option).
One or more data files, One or more control files, Two or more redo log files, Multiple
users/schemas, One or more rollback segments, One or more Tablespaces, Data dictionary
tables, User objects (table, indexes, views etc.)
SGA (Database buffer, Dictionary Cache Buffers, Redo log buffers, Shared SQL pool), SMON
(System Monitor),PMON (Process Monitor), LGWR (Log Write), DBWR (Data Base Write), ARCH
(ARCHiver), CKPT (Check Point), RECO, Dispatcher, User Process with associated PGS
You can do it at the OS level by deleting all the files of the database. The files to be deleted can be
found using:
1) select * from dba_data_files; 2) select * from v$logfile; 3) select * from v$controlfile; 4) archive
log list
5) initSID.ora 6) clean the UDUMP, BDUMP, scripts etc, 7) Cleanup the listener.ora and the
tnsnames.ora. Make sure that the oratab entry is also removed.
In fact DBA should never drop a database via OS level commands rather use GUI utility DBCA to
drop the database
What is difference between Logical Standby Database and Physical Standby database?
A physical or logical standby database is a database replica created from a backup of a primary
database. A physical standby database is physically identical to the primary database on a block-
for-block basis. It's maintained in managed recovery mode to remain current and can be set to
read only; archive logs are copied and applied.
A logical standby database is logically identical to the primary database. It is updated using SQL
statements
This query will returns NULL in the value column if you are using pfile and not spfile
3) SELECT COUNT(*) FROM v$spparameter WHERE value IS NOT NULL;
If the count is non-zero then the instance is using a spfile, and if the count is zero then it is using a
pfile:
SQL> SELECT DECODE(value, NULL, 'PFILE', 'SPFILE') "Init File Type"
A full backup is an operating system backup of all data files, on-line redo log
files and control file that constitute oracle database and the parameter.If you are using the Rman
for backup then in Rman full backup means Incremental backup on 0 level.
While taking hot backup (begin end backup) what will happens back end?
When we r taking hot backup (begin backup - end backup) the datafile header associated with
the datafiles in the corresponding Tablespace is frozen. So Oracle will stop updating the datafile
header but will continue to write data into datafiles. In hot backup oracle will generate more
redos this is because oracle will write out complete changed blocks to the redo log files.
Which is the best option used to move database from one server to another serve on same
network and Why?
Import – Export, Backup-Restore, Detach-Attach
Import-Export is the best option used to move database from one server to another serve on
same network. It reduces the network traffic.Import/Export works well if you’re dealing with
very small databases. If we have few million rows its takes minutes to copy when compared to
seconds using backup and restore.
Full backup: During a Full backup (Level 0) all of the block ever used in datafile are backed up.
The only difference between a level 0 incremental backup and a full backup is that a full backup
is never included in an incremental strategy.
Comulative Backup: During a cumulative (Level 0) the entire block used since last full backup
are backed up.
Give one method for transferring a table from one schema to another:
There are several possible methods: Export-Import, CREATE TABLE... AS SELECT or COPY.
What is the purpose of the IMPORT option IGNORE? What is its default setting?
The IMPORT IGNORE option tells import to ignore "already exists" errors. If it is not specified
the tables that already exist will be skipped. If it is specified, the error is ignored and the table’s
data will be inserted. The default value is N.
What happens when the DEFAULT and TEMP tablespace clauses are left out from CREATE
USER statements?
The user is assigned the SYSTEM tablespace as a default and temporary tablespace. This is bad
because it causes user objects and temporary segments to be placed into the SYSTEM tablespace
resulting in fragmentation and improper table placement (only data dictionary objects and the
system rollback segment should be in SYSTEM).
The Oracle system will use the default name of SYS_Cxxxx where xxxx is a system generated
number. This is bad since it makes tracking which table the constraint belongs to or what the
constraint does harder.
What happens if a Tablespace clause is left off of a primary key constraint clause?
This result in the index that is automatically generated being placed in then USERS default
tablespace. Since this will usually be the same tablespace as the table is being created in, this can
cause serious performance problems.
What happens if a primary key constraint is disabled and then enabled without fully
specifying the index clause?
The index is created in the user’s default tablespace and all sizing information is lost. Oracle
doesn’t store this information as a part of the constraint definition, but only as part of the index
definition, when the constraint was disabled the index was dropped and the information is gone.
Using hot backup without being in archive log mode, can you recover in the event of a
failure? Why or why not?
You can't recover the data because in archive log mode it take the backup of redo log files if it in
Active mode, If it in inactive mode then it is not possible to take the backup of redolog files once
the size is full, so in that case it is impossible to take hot backup
What causes the "snapshot too old" error? How can this be prevented or mitigated?
This is caused by large or long running transactions that have either wrapped onto their own
rollback space or have had another transaction write on part of their rollback space. This can be
prevented or mitigated by breaking the transaction into a set of smaller transactions or
increasing the size of the rollback segments and their extents.
A user is getting an ORA-00942 error yet you know you have granted them permission on
the table, what else should you check?
You need to check that the user has specified the full name of the object (SELECT empid FROM
scott.emp; instead of SELECT empid FROM emp;) or has a synonym that points to that object
(CREATE SYNONYM emp FOR scott.emp;)
A developer is trying to create a view and the database won’t let him. He has the
"DEVELOPER" role which has the "CREATE VIEW" system privilege and SELECT grants on
the tables he is using, what is the problem?
You need to verify the developer has direct grants on all tables used in the view. You can't create
a stored object with grants given through a role.
If you have an example table, what is the best way to get sizing data for the production
table implementation?
The best way is to analyze the table and then use the data provided in the DBA_TABLES view to
get the average row length and other pertinent data for the calculation. The quick and dirty way
is to look at the number of blocks the table is actually using and ratio the number of rows in the
table to its number of blocks against the number of expected rows.
How can you find out how many users are currently logged into the database? How can
you find their operating system id?
To look at the v$session or v$process views and check the current_logins parameter in the
v$sysstat view. If you are on UNIX is to do a ps -ef|grep oracle|wc -l? Command, but this only
works against a single instance installation.
Run the ANALYZE INDEX command on the index to validate its structure and then calculate the
ratio of LF_BLK_LEN/LF_BLK_LEN+BR_BLK_LEN and if it isn’t near 1.0 (i.e. greater than 0.7 or
so) then the index should be rebuilt or if the ratio BR_BLK_LEN/ LF_BLK_LEN+BR_BLK_LEN is
nearing 0.3. It is not so easy to decide so I personally suggest contact to the expert before going
to rebuild.
What is tkprof and how is it used?
The tkprof tool is a tuning tool used to determine CPU and execution times for SQL statements.
You use it by first setting timed_statistics to true in the initialization file and then turning on
tracing for either the entire database via the sql_trace parameter or for the session using the
ALTER SESSION command. Once the trace file is generated you run the tkprof tool against the
trace file and then look at the output from the tkprof tool. This can also be used to generate
explain plan output.
The EXPLAIN PLAN command is a tool to tune SQL statements. To use it you must have an
explain_table generated in the user you are running the explain plan for. This is created using the
utlxplan.sql script. Once the explain plan table exists you run the explain plan command giving
as its argument the SQL statement to be explained. The explain plan table is then queried to see
the execution plan of the statement. Explain plans can also be run using tkprof.
The SET option TERMOUT controls output to the screen. Setting TERMOUT OFF turns off screen
output. This option can be shortened to TERM.
How do you prevent Oracle from giving you informational messages during and after a
SQL statement execution?
A tablespace has a table with 30 extents in it. Is this bad? Why or why not.
Multiple extents in and of themselves aren’t bad. However if you also have chained rows this can
hurt performance.
You should always attempt to use the Oracle Flexible Architecture standard or another
partitioning scheme to ensure proper separation of SYSTEM, ROLLBACK, REDO LOG, DATA,
TEMPORARY and INDEX segments.
You see multiple fragments in the SYSTEM tablespace, what should you check first?
Ensure that users don’t have the SYSTEM tablespace as their TEMPORARY or DEFAULT
tablespace assignment by checking the DBA_USERS view.
What are some indications that you need to increase the SHARED_POOL_SIZE parameter?
Poor data dictionary or library cache hit ratios, getting error ORA-04031. Another indication is
steadily decreasing performance with all other tuning parameters the same.
Guideline for sizing db_block_size and db_multi_block_read for an application that does
many full table scans?
Oracle almost always reads in 64k chunks. The two should have a product equal to 64 or a
multiple of 64.
When looking at v$sysstat you see that sorts (disk) is high. Is this bad or good? If bad
-How do you correct it?
If you get excessive disk sorts this is bad. This indicates you need to tune the sort area
parameters in the initialization files. The major sort parameter is the SORT_AREA_SIZE
parameter.
When should you increase copy latches? What parameters control copy latches?
When you get excessive contention for the copy latches as shown by the "redo copy" latch hit
ratio. You can increase copy latches via the initialization parameter
LOG_SIMULTANEOUS_COPIES to twice the number of CPUs on your system.
Where can you get a list of all initialization parameters for your instance? How about an
indication if they are default settings or have been changed?
You can look in the init.ora file for an indication of manually set parameters. For all parameters,
their value and whether or not the current value is the default value, look in the v$parameter
view.
Describe hit ratio as it pertains to the database buffers. What is the difference between
instantaneous and cumulative hit ratio and which should be used for tuning?
The hit ratio is a measure of how many times the database was able to read a value from the
buffers verses how many times it had to re-read a data value from the disks. A value greater than
80-90% is good, less could indicate problems. If you simply take the ratio of existing parameters
this will be a cumulative value since the database started. If you do a comparison between pairs
of readings based on some arbitrary time span, this is the instantaneous ratio for that time span.
Generally speaking an instantaneous reading gives more valuable data since it will tell you what
your instance is doing for the time it was generated over.
Discuss row chaining, how does it happen? How can you reduce it? How do you correct it?
Row chaining occurs when a VARCHAR2 value is updated and the length of the new value is
longer than the old value and would not fit in the remaining block space. This results in the row
chaining to another block. It can be reduced by setting the storage parameters on the table to
appropriate values. It can be corrected by export and import of the effected table.
You are getting busy buffer waits. Is this bad? How can you find what is causing it?
Buffer busy waits could indicate contention in redo, rollback or data blocks. You need to check
the v$waitstat view to see what areas are causing the problem. The value of the "count" column
tells where the problem is, the "class" column tells you with what. UNDO is rollback segments,
DATA is data base buffers.
If you see contention for library caches how you can fix it?
If you see statistics that deal with "undo" what are they really talking about?
If a tablespace has a default pctincrease of zero what will this cause (in relationship to the
SMON process)?
The SMON process would not automatically coalesce its free space fragments.
If a tablespace shows excessive fragmentation what are some methods to defragment the
tablespace? (7.1,7.2 and 7.3 only)
In Oracle 7.0 to 7.2 The use of the 'alter session set events 'immediate trace name coalesce
level ts#'; command is the easiest way to defragment contiguous free space fragmentation. The
ts# parameter corresponds to the ts# value found in the ts$ SYS table. In version 7.3 the alter
tablespace coalesce; is best. If the free space is not contiguous then export, drop and import of
the tablespace contents may be the only way to reclaim non-contiguous free space.
If a select against the dba_free_space table shows that the count of tablespaces extents is greater
than the count of its data files, then it is fragmented.
You see the following on a status report: redo log space requests 23 redo log space wait
time 0 Is this something to worry about? What if redo log space wait time is high? How can
you fix this?
Since the wait time is zero, no problem. If the wait time was high it might indicate a need
for more or larger redo logs.
If you see a pin hit ratio of less than 0.8 in the estat library cache report is this a problem?
If so, how do you fix it?
This indicates that the shared pool may be too small. Increase the shared pool size.
If you see the value for reloads is high in the estat library cache report is this a matter for
concern?
Yes, you should strive for zero reloads if possible. If you see excessive reloads then increase the
size of the shared pool.
You look at the dba_rollback_segs view and see that there is a large number of shrinks and
they are of relatively small size, is this a problem? How can it be fixed if it is a problem?
A large number of small shrinks indicates a need to increase the size of the rollback segment
extents. Ideally you should have no shrinks or a small number of large shrinks. To fix this just
increase the size of the extents and adjust optimal accordingly.
You look at the dba_rollback_segs view and see that you have a large number of wraps is
this a problem?
A large number of wraps indicates that your extent size for your rollback segments are probably
too small. Increase the size of your extents to reduce the number of wraps. You can look at the
average transaction size in the same view to get the information on transaction size.
As long as they are all the same size this is not a problem. In fact, it can even improve
performance since Oracle would not have to create a new extent when a user needs one.
The answer here should show an understanding of separation of redo and rollback, data and
indexes and isolation of SYSTEM tables from other tables. An example would be to specify that at
least 7 disks should be used for an Oracle installation.
Disk Configuration:
They should indicate how they will handle archive logs and exports as well as long as they have a
logical plan for combining or further separation more or less disks can be specified.
You have installed Oracle and you are now setting up the actual instance. You have been
waiting an hour for the initialization script to finish, what should you check first to
determine if there is a problem?
Check to make sure that the archiver is not stuck. If archive logging is turned on during install a
large number of logs will be created. This can fill up your archive log destination causing Oracle
to stop to wait for more space.
When configuring SQLNET on the server what files must be set up?
When configuring SQLNET on the client what files need to be set up?
SQLNET.ORA, TNSNAMES.ORA
You have just started a new instance with a large SGA on a busy existing server.
Performance is terrible, what should you check for?
The first thing to check with a large SGA is that it is not being swapped out.
What OS user should be used for the first part of an Oracle installation (on UNIX)?
When should the default values for Oracle initialization parameters be used as is?
Never
How many control files should you have? Where should they be located?
How many redo logs should you have and how should they be configured for maximum
recoverability?
You should have at least 3 groups of two redo logs with the two logs each on a separate disk
spindle (mirrored by Oracle). The redo logs should not be on raw devices on UNIX if it can be
avoided.
A recursive relationship defines when or where a table relates to itself. It is considered as bad
when it is a hard relationship (i.e. neither side is a "may" both are "must") as this can result in it
not being possible to put in a top or perhaps a bottom of the table. For example in the
EMPLOYEE table you could not put in the PRESIDENT of the company because he has no boss, or
the junior janitor because he has no subordinates. These type of relationships are usually
resolved by adding a small intersection entity.
What does a hard one-to-one relationship mean (one where the relationship on both ends
is "must")?
This means the two entities should probably be made into one entity.
What is an artificial (derived) primary key? When should an artificial (or derived)
primary key be used?
A derived key comes from a sequence. Usually it is used when a concatenated key becomes too
cumbersome to use as a foreign key.
-UNIX-
How can you determine the number of SQLNET users logged in to the UNIX system?
SQLNET users will show up with a process unique name that begins with oracle, if you do a ps
-ef|grep oracle|wc -l you can get a count of the number of users.
What command is used to type files to the screen?
cat, more, pg
Yes
grep is a string search command that parses the specified string from the specified file or files
The system has a program that always includes the word nocomp in its name, how can
you determine the number of processes that are using this program?
ps -ef|grep *nocomp*|wc -l
The system administrator tells you that the system has not been rebooted in 6 months,
should he be proud of this?
Most UNIX systems should have a scheduled periodic reboot so file systems can be checked and
cleaned and dead or zombie processes cleared out. May be, Some UNIX systems do not clean up
well after themselves. Inode problems and dead user processes can accumulate causing possible
performance and corruption problems.
The finger command uses data in the passwd file to give information on system users.
The ">>" redirection symbol appends the output from the command specified into the file
specified. The file must already have been created.
If you are not sure what command does a particular UNIX function what is the best way to
determine the command?
The UNIX man -k command will search the man pages for the value specified. Review the results
from the command to find the command of interest.
How can you determine if an Oracle instance is up from the operating system level?
There are several base Oracle processes that will be running on multi-user operating systems,
these will be smon, pmon, dbwr and lgwr. Any answer that has them using their operating
system process showing feature to check for these is acceptable. For example, on UNIX ps -ef|
grep pmon will show what instances are up.
Users from the PC clients are getting messages indicating : ORA-06114: NETTCP: SID
lookup failure. What could the problem be?
Users from the PC clients are getting the following error stack:
ERROR: ORA-01034: ORACLE not available ORA-07318: smsget: open error when opening
sgadef.dbf file. HP-UX Error: 2: No such file or directory What is the probable cause?
The Oracle instance is shutdown that they are trying to access, restart the instance.
How can you determine if the SQLNET process is running for SQLNET V1? How about V2?
For SQLNET V1 check for the existence of the orasrv process. You can use the command "tcpctl
status" to get a full status of the V1 TCPIP server, other protocols have similar command formats.
For SQLNET V2 check for the presence of the LISTENER process(s) or you can issue the
command "lsnrctl status".
What file will give you Oracle instance status information? Where is it located?
The alert.ora log. It is located in the directory specified by the background_dump_dest parameter
in the v$parameter table.
Users are not being allowed on the system. The following message is received: ORA-00257
archiver is stuck. Connect internal only, until freed. What is the problem?
The archive destination is probably full, backup the archivelogs and remove them and the
archiver will re-start.
Where would you look to find out if a redo log was corrupted assuming you are using
Oracle mirrored redo logs?
There is no message that comes to the SQLDBA or SRVMGR programs during startup in this
situation, you must check the alert. log file for this information.
You attempt to add a datafile and get: ORA-01118: cannot add anymore datafiles: limit of
40 exceeded. What is the problem and how can you fix it?
When the database was created the db_files parameter in the initialization file was set to 40. You
can shutdown and reset this to a higher value, up to the value of MAX_DATAFILES as specified at
database creation. If the MAX_DATAFILES is set to low, you will have to rebuild the control file to
increase it before proceeding.
You look at your fragmentation report and see that smon has not coalesced any of you
tablespaces, even though you know several have large chunks of contiguous free extents.
What is the problem?
Check the dba_tablespaces view for the value of pct_increase for the tablespaces. If pct_increase
is zero, smon will not coalesce their free space.
Your users get the following error: ORA-00055 maximum number of DML locks exceeded?
What is the problem and how do you fix it?
The number of DML Locks is set by the initialization parameter DML_LOCKS. If this value is set to
low (which it is by default) you will get this error. Increase the value of DML_LOCKS. If you are
sure that this is just a temporary problem, you can have them wait and then try again later and
the error should clear.
You get a call from you backup DBA while you are on vacation. He has corrupted all of the
control files while playing with the ALTER DATABASE BACKUP CONTROLFILE command.
What do you do?
As long as all datafiles are safe and he was successful with the BACKUP controlfile command you
can do the following:
CONNECT INTERNAL STARTUP MOUNT (Take any read-only tablespaces offline before next step
Shutdown and backup the system, then restart If they have a recent output file from the ALTER
DATABASE BACKUP CONTROL FILE TO TRACE; command, they can use that to recover as well.
If no backup of the control file is available then the following will be required: CONNECT
INTERNAL STARTUP NOMOUNT CREATE CONTROL FILE .....; However, they will need to know
all of the datafiles, logfiles, and settings for MAXLOGFILES, MAXLOGMEMBERS,
MAXLOGHISTORY, MAXDATAFILES for the database to use the command.
You have taken a manual backup of a datafile using OS. How RMAN will know about it?
Whenever we take any backup through RMAN in the repository information of the backup is
recorded. The RMAN repository can be either controlfile or recovery catalog. However if you
take a backup through OS command then RMAN does not aware of that and hence recorded are
not reflected in the repository. This is also true whenever we create a new controlfile or a
backup taken by RMAN is transferred to another place using OS command then
controlfile/recovery catalog does not know about the prior backups of the database.
So in order to restore database with a new created controlfile we need to inform RMAN about
the backups taken before so that it can pick one to restore.
§ Add information of backup pieces and image copies in the repository that are on disk.
Catalog Datafile
Note that this datafile copy was taken backup either using the RMAN BACKUP AS COPY command
or by using operating system utilities in conjunction with ALTER TABLESPACE BEGIN/END
BACKUP.
To catalog all files in the currently enabled flash recovery area without prompting the user for
each one issue
In many cases you need to uncatalog command. Suppose you do not want a specific backup or
copy to be eligible to be restored but also do not want to delete it.
The size of the database is the total size of the datafiles that make up the tablespaces of the
database. These details are found in the dba_extents view.
How will you rectify if one of the rollback segments gets corrupted
The only option available is to restore and recover the database followed by opening the
database with resetlogs. In this case you will lose the entire prior database backup so must make
fresh backup.
How many days, we are going to retain the data after taking the backup. For example the
data which backed up today that will get expire in 90 days. That means, it is 90 days
retention policy for backup
You can configure retention policy command to create a persistent and automatic backup
retention policy. When a backup retention policy is in effect RMAN considers backups of
datafiles and control files as obsolete that is no longer needed for recovery according to criteria
that you specify in the CONFIGURE command. You can then use the REPORT OBSOLETE
command to view obsolete files and DELETE OBSOLETE to delete them. That means it is 90 days
retention policy for backup
What kind of backup you take Physical / Logical? Which one is better and Why?
Logical backup means backing up the individual database objects such as tables, views , indexes
using the utility called EXPORT, provided by Oracle. The objects exported in this way can be
imported into either same database or into any other database. The backed-up copy of
information is stored in a dumpfile, and this file can be read only using another utility called
IMPORT. There is no other way you can use this file. In this backup Oracle Export utility stores
data in Binary file at OS level.
Physical backups rely on the Operating System to make a copy of the physical files like data files,
log files, control files that comprise the database. In this backup physically CRD (datafile,
controlfile, redolog file) files are copied from one location to another (disk or tape)
We don't preferred logical backup. It is very slow and recoveries are almost not possible.
A Partial Backup is any operating system backup short of a full backup, taken while the
database is open or shut down.
What are the name of the available VIEW in oracle used for monitoring database is in
backup mode (begin backup).
V$backup : Status column of this view shows whether a tablespace is in hotbackup mode. The
status 'ACTIVE' shows the datafile to be in backup mode.
V$datafile_header : The fuzzy column also helps a dba to monitor datafile which are in backup
mode.
The fuzzy ‘NO’ indicates that the datafile is in hotbackup 9begin backup) mode.
NOTE : The database doesn't startup when a datafile is in backup mode. So put datafile back in the
normal mode before shutting down the database.
Tail Log Backup is the log backup taken after data corruption (Disaster). Even though there is
file corruption we can try to take log backup (Tail Log Backup). This will be used during point in
time recovery.
Consider a scenario where in we have full backup of 12:00 noon one Transactional log backup at
1:00 PM. The log backup is scheduled to run for every 1 hr. If disaster happens at 1:30 PM then
we can try to take tail log backup at 1:30 (after disaster). If we can take tail log backup then in
recovery first restore full backup of 12:00 noon then 1:00 PM log backup recovery and then last
tail backup of 1:30 (After Disaster).
If the master database is corrupt then surely others also do have the problems and thus the need
of MDF recovery comes to an immediate. However you can try out to rebuild it
with rebuild.exe and restore it.
You need to clean up the space and add more space in order to prevent this error in future.
SQL>Alter database tempfile ‘temp01.dbf’ resize 200M;
(
) D
The above query will displays for each sort segment in the database the tablespace the segment
resides in, the size of the tablespace, the amount of space within the sort segment that is
currently in use, and the amount of space available.
Whenever commit, checkpoint or redolog buffer is 1/3rd full, Time out occurs (3 sec.), 1 MB of
redo log buffer
- We can export from one user and import into another within the same database.
- We can export from one database and import into another database (but both source and
destination databases
- When migrating from one platform to another like from windows to sun Solaris then export is
the only method
"oratab" is a file created by Oracle in the /etc or /var/opt/oracle directory when installing
database software. Originally ORATAB was used for SQL*Net V1, but lately it is being used to list
the databases and software versions installed on a server.
database_sid:oracle_home_dir:Y|N
The Y|N flags indicate if the instance should automatically start at boot time (Y=yes, N=no).
Besides acting as a registry for what databases and software versions are installed on the server,
ORATAB is also used for the following purposes:
· Oracle's "dbstart" and "dbshut" scripts use this file to figure out which instances are to be
start up or shut down (using the third field, Y or N).
· The "oraenv" utility uses ORATAB to set the correct environment variables.
· One can also write Unix shell scripts that cycle through multiple instances using the
information in the oratab file.
In your database some blocks of particular datafile are corrupted. What statement will
you issue to know how many blocks are corrupted?
What is a flash back query? This feature is also available in 9i. What are the difference
between 9i and 10g (related to flash back query).
Flashback query:
· Flashback_Transactional_query view
· Flashback Table
· Flashback database
· AUM
How can the problem be resolved if a SYSDBA, forgets his password for logging into
enterprise manager?
3. Also you can enter as ‘/ as sysdba’ and then after change the password “Alter user sys
identified by xxx”;
How many maximum number of columns can be part of primary key in a table in 9i and
10g.
You can set primary key in a single table up to 16 columns of table in oracle 9i and 10g.
What is RAC?
Data Pumping is a data movement utility. This is a replacement to imp/exp utilities. The earlier
imp/exp utilities are also data movement utilities, but they work within the local servers only.
Where as, impdp/expdp (Data pumping) are very fast and perform data movements from one
database to another database on same as well as different host. In other words, it provides
secure transports.
What is Data Migration?
Data migration is actually the translation of data from one format to another format or from one
storage device to another storage device. Data migration is necessary when a company upgrades
its database or system software, either from one version to another or from one program to an
entirely different program.
CONTROLFILE, DATAFILE HEADERS, REDOLOG FILES (and hence ARCHIVE LOG FILES), DATA
BLOCK HEADERS but not in ALERT LOG file as it is not part of database.
By testing with the help of these tools tkprof or using explain plan. tkprof is available to DBA
Only where as explain plan can run programmer as well as DBA also. As well as tkprof generates
complexilty after sucessful execution only where as explain plan can show Oracle internal plan
& other details. Even though they are not alternatives for one to another. But both are designed
for one purpose only. They are two different tools they are engaged in different useful
situations also you can use STATSPACK to take Snaps while running those queries and get the
report with details of SQL taking more time to respond otherwise, you can search Top ten sql
with the following views:
SQL>SELECT * FROM V$SQL;
SQL>SELECT * FROM V$SQLAREA;
SQL>SELECT * FROM (SELECT rownum Substr(a.sql_text 1 200) sql_text
Trunc(a.disk_reads/Decode(a.executions 0 1 a.executions)) reads_per_execution a.buffer_gets
a.disk_reads a.executions a.sorts a.address FROM v$sqlarea a ORDER BY 3 DESC)WHERE
rownum < 10;
Groups of tables physically stored together because they share common columns and are often
used together is called clusters.
SHARED_POOL_RESERVE_SIZE
2. Invoke the DBNEWID utility (NID) from the command line using sys user.
Assuming the validation is successful the utility prompts for confirmation before performing the
actions.
Note: The SETNAME parameter tells the DBNEWID utility to only alter the database name.
SQL>SHUTDOWN IMMEDIATE
Set the DB_NAME initialization parameter in the initialization parameter file (PFILE) to the new
database name.
Note:The DBNEWID utility does not change the server parameter file (SPFILE). Therefore, if you
use SPFILE to start your Oracle database, you must re-create the initialization parameter file
from the server parameter file, remove the server parameter file, change the DB_NAME in the
initialization parameter file, and then re-create the server parameter file. Because you have
changed only the database name, and not the database ID, it is not necessary to use
the RESETLOGS option when you open the database. This means that all previous backups are
still usable.
SQL>Startup;
nid TARGET=sys/password@TSH3
DBA_Segments;
We cannot get the space of view because view does not have its own space it depend on base
table.
It is dba_free_space
Use VMSTAT to check the CPU enqueues or use also TOP and SAR commands for CPU load.
What would you use to improve performance on an insert statement that places millions
of rows into that table?
DML Triggers to be DISABLED and then ENABLED once the insert completed.
DISABLE the Clustered Index and then ENABLED once the insert completed.
If Monday take full backup and Tuesday it was cumulative backup and Wednesday we
taken incremental backup, Thursday some disaster happen then what type of recovery
and how it will take?
Restore the Monday full backup + Tuesday cumulative backup + Wednesday Incremental
backup. Becausecumulative and incremental clears the archives every backup
What is the difference between local managed Tablespace & dictionary managed
Tablespace ?
The basic diff between a locally managed tablespace and a dictionary managed tablespace is that
in the dictionary managed tablespace every time a extent is allocated or deallocated data
dictionary is updated which increases the load on data dictionary while in case of locally
managed tablespace the space information is kept inside the datafile in the form of bitmaps
every time a extent is allocated or deallocated only the bitmap is updated which removes burden
from data dictionary. The Tablespaces that record extent allocation/deallocation in the
dictionary are called dictionary managed tablespaces and tablespaces that record extent
allocation in the tablespace header are called locally managed tablespaces.
While installing the Oracle 9i ( 9.2) version, automatically system takes the space of
approximately 4 GB. That is fine.... Now, if my database is growing up and it is reaching the
4GB of my database space...Now, I would like to extend my Database space to 20 GB or 25
GB... what are the things i have to do?
The alternative better idea is that make the autoextend off and add more datafiles to the
Tablespace. Making a single datafile to a bigger size is risky. By making autoextend off you can
monitor the growth of the tablespace schedule a growth monitoring script with a threshold of 85
full.
The storage array should contain one or more spare disks (often called hot spares). When a
physical disk starts to report errors to the monitoringinfrastructure or fails suddenly the
firmware should immediately restore fault tolerance by mirroring the contents of the failed disk
onto a spare disk
When a user comes to you and asks that a particular SQL query is taking more time. How
will you solve this?
If you find the SQL Query (which make problem) then take a SQLTRACE with explain plan it will
show how the SQL query will executed by oracle depending upon the report you will tune your
database.
For example: one table has 10,000 records but you want to fetch only 5 rows but in that query
oracle does the full table scan. Only for 5 rows full table is scan is not a good thing so create an
index on the particular column by this way to tune the database.
The MAX_ENABLED_ROLES init.ora parameter limits the number of roles any user can have
enabled simultaneously. The default is 30 in both oracle 8i and 9i. When you create a role it is
enabled by default. If you create many roles, then you may exceed the MAX_ENABLED_ROLE
setting even if you are not the user of this role.
User Profiles:
The user profile are used to limits the amount of system and database resources available to a
user and to manage password restrictions. If no profile are created in a database then the default
profile are, which specify unlimited resources for all users, will be used.
>execute dbms_space_admin.tablespace_convert_to_local('tablespace_name');
>execute dbms_space_admin.tablespace_convert_from_local('tablespace_name');
What is a cluster Key ?
The related columns of the tables are called the cluster key. The cluster key is using a cluster
index and its value is stored only once for multiple tables in the cluster.
What are four performance bottlenecks that can occur in a database server and how are
they detected and prevented?
· CPU bottlenecks
Optimizer statistics are a collection of data that describes more details about the database and
the objects in the database. The optimizer statistics are stored in the data dictionary. They can
be viewed using data dictionary views similar to the following:
Because the objects in a database can constantly change statistics must be regularly updated so
that they accurately describe these database objects. Statistics are maintained automatically by
Oracle Database or you can maintain the optimizer statistics manually using the DBMS_STATS
package.
To use the SQL script UTLXPLAN.SQL to create a sample output table called PLAN_TABLE in your
schema.
To include the EXPLAIN PLAN FOR clause prior to the SQL statement.
After issuing the EXPLAIN PLAN statement to use one of the scripts or packages provided by
Oracle Database to display the most recent plan table output.
The execution order in EXPLAIN PLAN output begins with the line that is indented farthest to
the right. If two lines are indented equally then the top line is normally executed first.
Using the SQL Tuning Advisor and SQL Access Advisor you can invoke the query optimizer in
advisory mode to examine a given SQL statement or set of SQL statements and provide
recommendations to improve their efficiency. The SQL Tuning Advisor and SQL Access Advisor
can make various types of recommendations such as creating SQL profiles restructuring SQL
statements creating additional indexes or materialized views and refreshing optimizer statistics.
Additionally Oracle Enterprise Manager enables you to accept and implement many of these
recommendations in very few steps
The recovery catalog is an optional feature of RMAN though Oracle, recommends that you use it,
it isn’t required. One major benefit of the recovery catalog is that it stores metadata about
backups in a database that can be reported or queried. Catalog means you have a recovery
catalog database, nocatalog means that you are using the controlfile as rman repository. Of
course catalog option can only be used when recovery catalog is present (which is not
mandatory). From functional point of view there is no difference either taking backup in catalog
or nocatlaog mode.
A backup set contains one or more binary files in an RMAN-specific format. This file is known as
a backup piece. A backup set can contain multiple datafiles. For example, you can back up ten
datafiles into a single backup set consisting of a single backup piece. In this case, RMAN creates
one backup piece as output. The backup set contains only this backup piece.
What is an UTL_FILE? What are different procedures and functions associated with it?
The UTL_FILE package lets your PL/SQL programs read and write operating system (OS) text
files. It provides a restricted version of standard OS stream file input/output (I/O).
Subprogram -Description
FOPEN function-Opens a file for input or output with the default line size.
IS_OPEN function -Determines if a file handle refers to an open file.
FCLOSE procedure -Closes a file.
FCLOSE_ALL procedure -Closes all open file handles.
GET_LINE procedure -Reads a line of text from an open file.
PUT procedure-Writes a line to a file. This does not append a line terminator.
NEW_LINE procedure-Writes one or more OS-specific line terminators to a file.
PUT_LINE procedure -Writes a line to a file. This appends an OS-specific line terminator.
PUTF procedure -A PUT procedure with formatting.
FFLUSH procedure-Physically writes all pending output to a file.
FOPEN function -Opens a file with the maximum line size specified.
Instance is a combination of memory structure and process structure. Memory structure is SGA
(System or Shared Global Area) and Process structure is background processes.
Components of SGA:
Database Buffer Cache: It is further divided into Library Cache and Data Dictionary Cache or
Row Cache,
Shared Pool/large pool/stream pool/java pool
Background Process:
When Oracle starts an instance, it reads the initialization parameter file to determine the values
of initialization parameters. Then, it allocates an SGA, which is a shared area of memory used for
database information, and creates background processes. At this point, no database is associated
with these memory structures and processes.
The database name, The timestamp of database creation, The names and locations of associated
datafiles and redo log files, Tablespace information, Datafile offline ranges, The log
history, Archived log information, Backup set and backup piece information, Backup datafile and
redo log information, Datafile copy information, The current log sequence number
To Start an instance, oracle server need a parameter file which contains information about the
instance, oracle server searches file in following sequence:
1) SPFILE ------ if finds instance started .. Exit
2) Default SPFILE -- if it is spfile is not found
3) PFILE -------- if default spfile not find, instance started using pfile.
4) Default PFILE -- is used to start the instance.
When an Oracle instance fails, Oracle performs an instance recovery when the associated
database is re-started.
Instance recovery occurs in two steps:
Cache recovery: Changes being made to a database are recorded in the database buffer cache.
These changes are also recorded in online redo log files simultaneously. When there are enough
data in the database buffer cache, they are written to data files. If an Oracle instance fails before
the data in the database buffer cache are written to data files, Oracle uses the data recorded in
the online redo log files to recover the lost data when the
associated database is re-started. This process is called cache recovery.
Transaction recovery: When a transaction modifies data in a database, the before image of the
modified data is stored in an undo segment. The data stored in the undo segment is used to
restore the original values in case a transaction is rolled back. At the time of an instance failure,
the database may have uncommitted transactions. It is possible that changes made by these
uncommitted transactions have gotten saved in data files. To maintain read consistency, Oracle
rolls back all uncommitted transactions when the associated database is re-started. Oracle uses
the undo data stored in undo segments to accomplish this. This process is called transaction
recovery.
Log writer (LGWR) writes redo log buffer contents Into Redo Log Files. Log writer does this
every three seconds, when the redo log buffer is 1/3 full and immediately before the Database
Writer (DBWn) writes its changed buffers into the data file.
How do you control number of Datafiles one can have in an Oracle database?
When starting an Oracle instance, the database's parameter file indicates the amount of SGA
space to reserve for datafile information; the maximum number of datafiles is controlled by the
DB_FILES parameter. This limit applies only for the life of the instance.
Default maximum datafile is 255 that can be defined in the control file at the time of database
creation.
It can be increased by setting the initialization parameter value up to higher at the time of
database creation. Setting this value too higher can cause DBWR issues.
Before 9i Maximum number of datafile in database was 1022.After 9i the limit is applicable to the
number of datafile in the Tablespace.
What is a Tablespace?
A tablespace is a logical storage unit within the database. It is logical because a tablespace is not
visible in the file system of the machine on which database resides. A tablespace in turn consists
of at least one datafile, which, in tune are physically located in the file system of the server. The
tablespace builds the bridge between the Oracle database and the file system in which the table's
or index' data is stored.
The purpose of redo log file is to record all changes made to the data during the recovery of
database. It always advisable to have two or more redo log files and keep them in a separate
disk, so you can recover the data during the system crash.
Which default Database roles are created when you create a Database?
What is a Checkpoint?
1. Every block in the buffer cache is written to the data files. That is, it synchronizes the data
blocks in the buffer cache with the datafiles on disk. It's the DBWR that writes all modified
database blocks back to the datafiles.
The update of the datafile headers and the control files is done by the LGWR (if CKPT is enabled).
As of version 8.0, CKPT is enabled by default. The date and time of the last checkpoint can be
retrieved through checkpoint_time in v$datafile_header. The SCN of the last checkpoint can be
found in v$database as checkpoint_change#.
This would turn on autoextend, grab new disk space of 10m when needed and have no upper
limit on the size of the datafile.
Note: This would be bad on a 32bit machine, where the max size is typically 4gig.
It is the area in SGA that allows sharing of parsed SQL statements among concurrent users. It is
to store the SQL statements so that the identical SQL statements do not have to be parsed each
time they're executed.
The shared pool is the part of the SGA where (among others) the following things are stored:
Database Buffer cache is one of the most important components of System Global Area (SGA).
Database Buffer Cache is the place where data blocks are copied from datafiles to perform SQL
operations. Buffer Cache is shared memory structure and it is concurrently accessed by all
server processes. Oracle allows different block size for different tablespaces. A standard block
size is defined in DB_BLOCK_SIZE initialization parameter. System tablespace uses standard
block size. DB_CACHE_SIZE parameter is used to define size for Database buffer cache. For
example to create a cache of 800 MB, set parameter as below
DB_CACHE_SIZE=800M
If you have created a tablesapce with bock size different from standard block size, for example
your standard block size is 4k and you have created a tablespace with 8k block size then you
must create a 8k buffer cache as
DB_8K_CACHE_SIZE=256
Maximum number of log files a database can accommodate depends on the parameter
"MAXLOGMEMBERS" specified during database creation. In a database we can create 255
maximum redo log files. It depends on what you specified for MAXLOGFILES during database
creation (manually) or what you specified for "Maximum no. of redo log files" with DBCA.
PGA_AGGREGATE_TARGET is an Oracle server parameter that specifies the target aggregate PGA
memory available to all server processes attached to the instance. Some of the properties of the
PGA_AGGREGATE_TARGET parameter are given below:
Parameter type: Big integer
Syntax: PGA_AGGREGATE_TARGET = integer [K M G]•Default value: 20% of SGA size or 10MB,
whichever is greater or modifiable by ALTER SYSTEM
Large Pool is an optional memory structure used for the following purposes: -
(1) Session information for shared server
(2) I/O server processes
(3) Parallel queries
(4) Backup and recovery if using through RMAN.
The role of Large Pool is important because otherwise memory would be allocated from the
Shared pool. Hence Large pool also reduces overhead of Shared pool.
PCTINCREASE refers to the percentage by which each next extent (beginning with the third
extend) will grow. The size of each subsequent extent is equal to the size of the previous extent
plus this percentage increase.
PCTFREE is a block storage parameter used to specify how much space should be left in a
database block for future updates. For example, for PCTFREE=10, Oracle will keep on adding
new rows to a block until it is 90% full. This leaves 10% for future updates (row expansion).
When using Oracle Advanced Compression, Oracle will trigger block compression when
the PCTFREE is reached. This eliminates holes created by row deletions and maximizes
contiguous free space in blocks.
PCTUSED is a block storage parameter used to specify when Oracle should consider a database
block to be empty enough to be added to the freelist. Oracle will only insert new rows in blocks
that is enqueued on the freelist. For example, if PCTUSED=40, Oracle will not add new rows to
the block unless sufficient rows are deleted from the block so that it falls below 40% empty.
There are two circumstances when this can occur, the data for a row in a table may be too large
to fit into a single data block. This can be caused by either row chaining or row migration.
Chaining: Occurs when the row is too large to fit into one data block when it is first inserted. In
this case, Oracle stores the data for the row in a chain of data blocks (one or more) reserved for
that segment. Row chaining most often occurs with large rows, such as rows that contain a
column of data type LONG, LONG RAW, LOB, etc. Row chaining in these cases is unavoidable.
Migration: Occurs when a row that originally fitted into one data block is updated so that the
overall row length increases, and the block’s free space is already completely filled. In this case,
Oracle migrates the data for the entire row to a new data block, assuming the entire row can fit
in a new block. Oracle preserves the original row piece of a migrated row to point to the new
block containing the migrated row: the rowid of a migrated row does not change. When a row is
chained or migrated, performance associated with this row decreases because Oracle must
scan more than one data block to retrieve the information for that row.
1. INSERT and UPDATE statements that cause migration and chaining perform poorly,
because they perform additional processing.
2. SELECTs that use an index to select migrated or chained rows must perform additional
I/Os.
Detection: Migrated and chained rows in a table or cluster can be identified by using the
ANALYZE command with the LIST CHAINED ROWS option. This command collects information
about each migrated or chained row and places this information into a specified output table. To
create the table that holds the chained rows,
execute script UTLCHAIN.SQL.
SQL> ANALYZE TABLE scott.emp LIST CHAINED ROWS;
SQL> SELECT * FROM chained_rows;
You can also detect migrated and chained rows by checking the ‘table fetch continued row’
statistic in the v$sysstat view.
SQL> SELECT name, value FROM v$sysstat WHERE name = ‘table fetch continued row’;
Although migration and chaining are two different things, internally they are represented by
Oracle as one. When detecting migration and chaining of rows you should analyze carefully what
you are dealing with.
What is Ora-01555 - Snapshot Too Old error and how do you avoid it?
1. Increase the size of rollback segment. (Which you have already done)
3. Add a big rollback segment and allot your transaction to this RBS.
4. There is also possibility of RBS getting shrunk during the life of the query by setting optimal.
A Locally Managed Tablespace is a tablespace that manages its own extents maintaining a
bitmap in each data file to keep track of the free or used status of blocks in that data file. Each bit
in the bitmap corresponds to a block or a group of blocks. When the extents are allocated or
freed for reuse, Oracle changes the bitmap values to show the new status of the blocks. These
changes do not generate rollback information because they do not update tables in the data
dictionary (except for tablespace quota information), unlike the default method of Dictionary -
Managed Tablespaces.
Yes, we can audit the select statements. Check out the below example:
SQL> show parameter audit
SQL> begin
In HR schema:
Table created.
SQL> insert into bankim values (‘bankim’, 10);
1 row created.
1 row created.
SQL> select * from bankim;
NAME ROLL
———- ———-
bankim 10
bankim2 20
NAME
———-
bankim
bankim2
In sys schema:
The dbms_fga Package is the central mechanism for the FGA is implemented in the package
dbms_fga, where all the APIs are defined. Typically, a user other than SYS is given the
responsibility of maintaining these policies. With the convention followed earlier, we will go
with the user SECUSER, who is entrusted with much of the security features. The following
statement grants the user SECUSER enough authority to create and maintain the auditing
facility.
The biggest problem with this package is that the polices are not like regular objects with
owners. While a user with execute permission on this package can create policies, he or she can
drop policies created by another user, too. This makes it extremely important to secure this
package and limit the use to only a few users who are called to define the policies, such as
SECUSER, a special user used in examples.
The CBO is used to design an execution plan for SQL statement. The CBO takes an SQL statement
and tries to weigh different ways (plan) to execute it. It assigns a cost to each plan and chooses
the plan with smallest cost.
CBO needs some statistics in order to assess the cost of the different access plans. These
statistics includes:
Size of tables, Size of indexes, number of rows in the tables, number of distinct keys in an index,
number of levels in a B* index, average number of blocks for a value, average number of leaf
blocks in an index
sqlplus scott/tiger
exec dbms_stats.gather_table_stats ( -
ownname => 'SCOTT', -
tabname => 'EMP', -
estimate_percent => dbms_stats.auto_sample_size, -
method_opt => 'for all columns size auto', -
cascade => true, -
degree => 5 - )
/
sqlplus scott/tiger
exec dbms_stats.gather_schema_stats ( -
ownname => 'SCOTT', -
options => 'GATHER', -
estimate_percent => dbms_stats.auto_sample_size, -
method_opt => 'for all columns size auto', -
cascade => true, -
degree => 5 - )
DBMS_STATS can collect optimizer statistics on the following levels, see Oracle Manual
GATHER_DATABASE_STATS
GATHER_DICTIONARY_STATS
GATHER_FIXED_OBJECTS_STATS
GATHER_INDEX_STATS
GATHER_SCHEMA_STATS
GATHER_SYSTEM_STATS
GATHER_TABLE_STATS
· Volatile tables that are being deleted or truncated and rebuilt during the course of the day.
· Objects which are the target of large bulk loads which add 10% or more to the object’s total
size.
So you may wish to manually gather statistics of those objects in order to choose the optimizer
the best execution plan. There are two ways to gather statistics.
To delete statistics:
You should create indexes on columns that are used frequently in WHERE clauses.
You should create indexes on columns that are used frequently to join tables.
You should create indexes on columns that are used frequently in ORDER BY clauses.
You should create indexes on columns that have few of the same values or unique values
in the table.
You should not create indexes on small tables (tables that use only a few blocks) because
a full table scan may be faster than an indexed query.
If possible, choose a primary key that orders the rows in the most appropriate order.
If only one column of the concatenated index is used frequently in WHERE clauses, place
that column first in the CREATE INDEX statement.
If more than one column in a concatenated index is used frequently in WHERE clauses,
place the most selective column first in the CREATE INDEX statement.
Bitmap indexes: compact; work best for columns with a small set of values
B-Tree is an indexing technique most commonly used in databases and file systems where
pointers to data are placed in a balance tree structureso that all references to any data can be
accessed in an equal time frame. It is also a tree data structure which keeps data sorted so that
searching, inserting and deleting can be done in logarithmic amortized time.
A table is having few rows, should you create indexes on this table?
You should not create indexes on small tables (tables that use only a few blocks) because a full
table scan may be faster than an indexed query.
A Column is having many repeated values which type of index you should create on this
column
B-Tree index is suitable if the columns being indexed are high cardinality (number of repeated
values). In fact for this situation a bitmap index is very useful but bitmap index are vary
expensive.
There is no thumb rule “when you should rebuild the index”. According to expert it depends
upon your database situation:
When the data in index is sparse (lots of holes in index, due to deletes or updates) and your
query is usually range based or If Blevel >3 then takes index in rebuild consideration; desc
DBA_Indexes;
Because when you rebuild indexes then database performance goes down.
In fact binary tree index can never be unbalanced. Binary tree performance is good for both
small and large tables and does not degrade with the growth of table.
Yes, we can build index online. It allows performing DML operation on the base table during
index creation. You can use the statements:
A Table Lock is required on the index base table at the start of the CREATE or REBUILD process
to guarantee DDL information. A lock at the end of the process also required to merge change
into the final index structure.
minextents 2
Yes. We can perform online table redefinition with the Enterprise Manager Reorganize Objects
wizard or with the DBMS_REDEFINITION package.
It provides a mechanism to make table structure modification without significantly affecting the
table availability of the table. When a table is redefining online it is accessible to both queries
and DML during the redefinition process.
· One cannot redefine Materialized Views (MViews) and tables with MViews or MView Logs
defined on them.
· One cannot redefine tables with BFILE, LONG or LONG RAW columns
· Table redefinition cannot be done in NOLOGGING mode (watch out for heavy archiving)
Yes, we can do this through resource manager. The Database Resource Manager gives a database
administrators more control over resource management decisions, so that resource allocation
can be aligned with an enterprise's business objectives.
Create an active session pool. This pool consists of a specified maximum number of user
sessions allowed to be concurrently active within a group of users. Additional sessions
beyond the maximum are queued for execution, but you can specify a timeout period,
after which queued jobs terminate.
Allow automatic switching of users from one group to another group based on
administrator-defined criteria. If a member of a particular group of users creates a
session that runs for longer than a specified amount of time, that session can be
automatically switched to another group of users with different resource requirements.
Prevent the execution of operations that are estimated to run for a longer time than a
predefined limit
Create an undo pool. This pool consists of the amount of undo space that can be
consumed in by a group of users.
Users normally use the "CONNECT" statement to connect from one database user to another.
However, DBAs can switch from one user to another without a password. Of course it is not
advisable to bridge Oracle's security, but look at this example:
F894844C34402B67
OK, we're in. Let's quickly change the password back before anybody notices.
User altered.
Method1:
Method2:
Method3:
DELETE SHAAN
WHERE rowid IN
FROM SHAAN );
Method4:
( select min(rowid)
Method5:
Method6:
ASSM can be specified only with the locally managed tablespaces (LMT). The CREATE
TABLESPACE statement has a new clause SEGMENT SPACE MANAGEMENT. Oracle uses bitmaps
to manage the free space. A bitmap, in this case, is a map that describes the status of each data
block within a segment with respect to the amount of space in the block available for inserting
rows. As more or less space becomes available in a data block, its new state is reflected in the
bitmap.
CREATE TABLESPACE myts DATAFILE '/oradata/mysid/myts01.dbf' SIZE 100M
EXTENT MANAGEMENT LOCAL UNIFORM SIZE 2M
SEGMENT SPACE MANAGEMENT AUTO;
If COMPRESS=Y, the INITIAL storage parameter is set to the total size of all extents allocated for
the object. The change takes effect only when the object is imported.
Setting CONSISTENT=Y exports all tables and references in a consistent state. This slows the
export, as rollback space is used. If CONSISTENT=N and a record is modified during the export,
the data will become inconsistent.
What is the difference between Direct Path and Convention Path loading?
When you use SQL loader by default it use conventional path to load data. This method competes
equally with all other oracle processes for buffer resources. This can slow the load. A direct path
load eliminates much of the Oracle database overhead by formatting Oracle data blocks and
writing the data blocks directly to the database files. If load speed is most important to you, you
should use direct path load because it is faster.
When you create a partitioned table, you should create an index on the table. The index may be
partitioned according to the same range values that were used to partition the
table. Local keyword in the index partition tells oracle to create a separate index for each
partition of the table. TheGlobal clause in create index command allows you to create a non-
partitioned index or to specify ranges for the index values that are different from the ranges for
the table partitions. Local indexes may be easier to manage than global indexes however, global
indexes may perform uniqueness checks faster than local (portioned) indexes perform them.
Oracle Database creates server processes to handle the requests of user processes connected to
an instance.
Your database is always enabled to allow dedicated server processes, but you must specifically
configure and enable shared server by setting one or more initialization parameters.
Method 1:
Export the table, drop the table, create the table definition in the new tablespace, and then
import the data (imp ignore=y).
Method 2:
Create a new table in the new tablespace with the "CREATE TABLE x AS SELECT * from y"
command:
Then drop the original table and rename the temporary table as the original:
Note: After step #1 or #2 is done, be sure to recompile any procedures that may have been
invalidated by dropping the table. Prefer method #1, but #2 is easier if there are no indexes,
constraints, or triggers. If there are, you must manually recreate them.
Method 3:
SELECT * FROM SM$TS_FREE;
SELECT TABLESPACE_NAME, SUM(BYTES) FROM DBA_FREE_SPACE GROUP BY TABLESPACE_N
AME;
Yes, the view can be created from other view by directing a select query to use the other view
data.
What happens, if you not specify Dictionary option with the start option in case of
LogMinor concept?
LogMiner is a recovery utility. You can use it to recover the data from oracle redo log and
archive log file. The Oracle LogMiner utility enables you to query redo logs through a SQL
interface. Redo logs contain information about the history of activity on a database.
Benefit of LogMiner?
2. Perform table specific undo operation to return the table to its original state. LogMiner
reconstruct the SQL statement in reverse order from which they are executed.
3. It helps in performance tuning and capacity planning. You can determine which table gets
the most update and insert. That information provides a historical perspective on disk access
statistics, which can be used for tuning purpose.
4. Performing post auditing; LogMiner is used to track any DML and DDL performed on
database in the order they were executed.
Oracle DataGuard is a tools that provides data protection and ensures disaster recovery for
enterprise data. It provides comprehensive set of services that create, maintain, manage, and
monitor one or more standby databases to enable production Oracle databases to survive
disasters and data corruption. Dataguard maintains these standsby databases as transitionally
consistent copies of the production database. Then, if the production database becomes failure
Data Guard can switch any standby database to the production role, minimizing the downtime
associated with the outage. Data Guard can be used with traditional backup, restoration, and
cluster techniques to provide a high level of data protection and data availability.
A standby database is a transitionally consistent copy of the primary database. Using a backup
copy of the primary database, you can create up to9 standby databases and incorporate them
in a Data Guard configuration. Once created, Data Guard automatically maintains each standby
database by transmitting redo data from the primary database and then applying the redo to the
standby database.
Similar to a primary database, a standby database can be either a single-instance Oracle
database or an Oracle Real Application Clusters database. A standby database can be either
a physical standby database or a logical standby database:
Provides a physically identical copy of the primary database on a block-for-block basis. The
database schema, including indexes, is the same. A physical standby database is kept
synchronized with the primary database, though Redo Apply, which recovers the redo data,
received from the primary database and applies the redo to the physical standby database.
Logical Standby database contains the same logical information as the production database,
although the physical organization and structure of the data can be different. The logical standby
database is kept synchronized with the primary database though SQL Apply, which transforms
the data in the redo received from the primary database into SQL statements and then executing
the SQL statements on the standby database.
If you are going to setup standby database what will be your Choice Logical or Physical?
We do not see such issues with logical standby database. We can open up the database in
normal mode and make it available to the users. At the same time, we can apply archived logs
received from primary database.
If the primary database needed to support pretty large user community for the OLTP system and
pretty large “Reporting Group” then better to uselogical standby as primary database instead of
physical database.
· Require the same hardware architecture on the primary and all standby site.
· Does not require the same OS version and release on the primary and secondary site.
· Each Primary and secondary database must have its own database.
Failover is the operation of bringing one of the standby databases online as the new primary
database when failure occurs on the primary database and there is no possibility of recover
primary database in a timely manner. The switchover is a situation to handle planned
maintenance on the primary database. The main difference between switchover operation and
failover operation is that switchover is performed when primary database is still available or it
does not require a flash back or re-installation of the original primary database. This allows the
original primary database to the role of standby database almost immediately. As a result
schedule maintenance can performed more easily and frequently.
When you use WHERE clause and when you use HAVING clause?
HAVING clause is used when you want to specify a condition for a group function and it is
written after GROUP BY clause The WHERE clause is used when you want to specify a condition
for columns, single row functions except group functions and it is written before GROUP BY
clause if it is used.
A cursor is a PL/SQL block used to fetch more than one row in a Pl/SQl block. PL/SQL declares a
cursor implicitly for all SQL data manipulation statements, including quries that return only one
row. However, queries that return more than one row you must declare an explicit cursor or use
a cursor FOR loop.
Explicit cursor is a cursor in which the cursor name is explicitly assigned to a SELECT statement
via the CURSOR...IS statement. An implicit cursor is used for all SQL statements Declare, Open,
Fetch, Close. An explicit cursors are used to process multirow SELECT statements An implicit
cursor is used to process INSERT, UPDATE, DELETE and single row SELECT. .INTO statements.
You have just had to restore from backup and do not have any control files. How would
you go about bringing up this database?
I would create a text based backup control file, stipulating where on disk all the data files where
and then issue the recover command with the using backup control file clause.
A table is classified as a parent table and you want to drop and re-create it. How would
you do this without affecting the children tables?
Disable the foreign key constraint to the parent, drop the table, re-create the table, and enable
the foreign key constraint.
First we start up RMAN with a connection to the catalog and the target, making a note of the
DBID in the banner:
Next we connect to the RMAN catalog owner using SQL*Plus and issue the following statement:
The resulting key and id can then be used to unregister the database:
If a database was terminated while one of its tablespaces was in BACKUP MODE (ALTER
TABLESPACE xyz BEGIN BACKUP;), it will tell you that media recovery is required when you try
to restart the database. The DBA is then required to recover the database and apply all archived
logs to the database. However, from Oracle 7.2, one can simply take the individual datafiles out
of backup mode and restart the database.
One can select from V$BACKUP to see which datafiles are in backup mode From Oracle9i
onwards, the following command can be used to take all of the datafiles out of hotbackup mode:
Note: This command must be issued when the database is mounted, but not yet opened.
When a tablespace is in backup mode, Oracle will stop updating its file headers, but will continue
to write to the data files. When in backup mode, Oracle will write complete changed blocks to the
redo log files. Because of this, increased log activity and archiving during on-line backups. To
solve this problem, simply switch to RMAN backups.
Difference Consistent and Inconsistent Backup
The backup taken in shutdown state or in same point in time are referred to as consistent. Unlike
an inconsistent backup, a consistent whole database backup does not require recovery after it is
restored, here all header of datafile belongs to writable tablespace have the same SCN. These
datafile donot have any change past this check point SCN. The SCN of datafile header matches
exactly controlfile checkpoint.
An inconsistent backup is a backup of one or more database files that you make while the
database is open or after the database has shut down abnormally. This means that the files in the
backup contain data taken from different points in time. This can occur because the datafiles are
being modified as backups are being taken. Not any of the above mentioned properties are exist
here. A recovery (Applying all the archive and online redo logs) is needed in order to make the
backup consistent.
Restoring involves copying backup files from secondary storage (backup media) to disk. This can
be done to replace damaged files or to copy/move a database to a new location.
Recovery is the process of applying redo logs to the database to roll it forward. One can roll-
forward until a specific point-in-time (before the disaster occurred), or roll-forward until the
last transaction recorded in the log files.
Complete recovery involves using redo data or incremental backups combined with a backup of
a database, tablespace, or datafile to update it to the most current point in time. It is
called complete because Oracle applies all of the redo changes contained in the archived and
online logs to the backup. Typically, you perform complete media recovery after a media failure
damages datafiles or the control file.
Incomplete recovery, or point-in-time recovery we do not apply all of the redo records
generated after the most recent backup or when archive redo log is missing.
Because you are not completely recovering the database to the most current time, you must tell
Oracle when to terminate recovery. You can perform the following types of media recovery.
Time based Recovery, Cancel based Recovery, Change based Recovery, Log sequence Recovery
What happens when we open the database with Resetlogs option after incomplete
recovery?
A hot (or on-line) backup is a backup performed while the database is open and available for use
(read and write activity). Except for Oracle exports, one can only do on-line backups when the
database is ARCHIVELOG mode. A cold (or off-line) backup is a backup performed while the
database is off-line and unavailable to its users. Cold backups can be taken regardless if the
database is in ARCHIVELOG or NOARCHIVELOG mode.
It is easier to restore from off-line backups as no recovery (from archived logs) would be
required to make the database consistent. Nevertheless, on-line backups are less disruptive and
doesn't require database downtime.
Point-in-time recovery (regardless if you do on-line or off-line backups) is only available when
the database is in ARCHIVELOG mode.
Views evaluate the data in the tables underlying the view definition at the time the view is
queried. It is a logical view of your tables, with no data stored anywhere else. The upside of a
view is that it will always return the latest data to you. The downside of a view is that its
performance depends on how good a select statement the view is based on. If the select
statement used by the view joins many tables, or uses joins based on non-indexed columns, the
view could perform poorly.
Materialized views are similar to regular views, in that they are a logical view of your data
(based on a select statement), however, the underlying query result set has been saved to a
table. The upside of this is that when you query a materialized view, you are querying a table,
which may also be indexed. Materialized views having several other advantages over simple
view.
How to find the last refresh of your database (when the recovery with resetlogs
performed)?
If the cloned database has been opened with RESETLOGS option, you can try checking out
V$DATABASE.RESETLOGS_TIME. if the V$DATABASE.CREATED is not equal to
V$DATABASE.RESETLOGS_TIME...there is a possibility that it might be opened with resetlogs
option. I don't have the required set up to check and confirm this myself....but this is something
you can get it a shot.
Command to find files created a day before
Initially Flashback Database was enabled but noticed Flashback was disabled
automatically long time ago. What is the Issue?
Reason:
It could be because the flashback area 100% Once Flashback Area become 100% full then oracle
will log in Alert that Flashback will be disabled and it will automatically turn off Flash Back
without user intervention.
It depends on how you killed the process. If you did and alter system kill session you should be
able to look at the used_ublk block in v$transaciton to get an estimate for the rollback being
done. If you killed to server process in the OS and pmon is recovering the transaction you can
look at V$FAST_START_TRANSACTIONS view to get the estimate
Rman
Once current redolog file is damaged, instance is aborted and it needs recovery upto undamaged
part. Only undamaged part can be recovered. Here DBA must apply time based recovery, means
it can be a point in time or specified by SCN. It leads to incomplete recovery
Application Tuning:
Experience showed that approximately 80% of all Oracle system performance problems are
resolved by coding optimal SQL. Also consider proper scheduling of batch tasks after peak
working hours.
Memory Tuning:
Properly size your database buffers (shared pool, buffer cache, log buffer, etc) by looking at your
buffer hit ratios. Pin large objects into memory to prevent frequent reloads.
Study database locks, latches and wait events carefully and eliminate where possible.
Monitor and tune operating system CPU, I/O and memory utilization. For more information,
read the related Oracle FAQ dealing with your specific operating system.
ORA-00001: Unique constraint (...) violated - You are importing duplicate rows. Use
IGNORE=NO to skip tables that already exist (imp will give an error if the object is re-created).
ORA-01555: Snapshot too old - Ask your users to STOP working while you are exporting or use
parameter CONSISTENT=NO
ORA-01562: Failed to extend rollback segment - Create bigger rollback segments or set
parameter COMMIT=Y while importing
IMP-00015: Statement failed ... object already exists... - Use the IGNORE=Y import parameter to
ignore these errors, but be careful as you might end up with duplicate rows.
By mistake a use drop or truncate a Table then what is the best method to recover it?
Restore and recover the primary database to a point in time before the drop. This is an extreme
measure for one table as the entire database goes back in time.
Restore and recover the tablespace to a point in time before the drop. This is a better option, but
again, it takes the entire tablespace back in time.
Restore and recover a subset of the database as a DUMMY database to export the table data and
import it into the primary database. This is the best option as only the dropped table goes back
in time to before the drop.
Connected.
PASSWORD
--------------- ---------------
F894844C34402B67
User altered.
Connected.
OK, we're in. Let's quickly change the password back before anybody notices.
User altered.
While applying the CPU Patch why we need to update the Oracle Inventory?
Because when you apply the CPU it updates the oracle binaries.
Locks are used to protect the data or resources from the simultaneous use of them by multiple
sessions which might set them in inconsistent state. Locks are external mechanism, means user
can also set locks on objects by using various oracle statements.
Latches are for the same purpose but works at internal level. Latches are used to Protect and
control access to internal data structures like various SGA buffers. They are handled and
maintained by oracle and we can’t access or set it.
Setting the audit_trail parameter in the database to “db”, it generates lot of records in
sys.aud$ table. Can you suggest any method to overcome this issue?
1. When you set audit it does audit for every single activity on the database. So it may lead into
performance problem.
You have to disable every single audit(<> noaudit) before or after you set the parameter and
then enable one by one based on the requirement.
2. You should monitor the growth of sys.aud$ and archive it properly or maintain the space.
How do you remove an SPFILE parameter (not change the value of, but actually purge it
outright)?
Use "ALTER SYSTEM RESET ..." (For database versions 9i and up)
Syntax:
If the resultant of sub query is small then ‘IN’ is typically more appropriate where as resultant of
sub query is big/large/long then ‘EXIST’ is more appropriate. The ‘Exist’ always results full scan
of table where as first query can make use of index on Table.
Is Oracle really quicker on Windows than Solaris?
I found in my experience that Yes, windows perform better on comparable hardware just about
any UNIX box. I am working on Windows but once I installed Solaris trying to test. I found the
windows installations always outperformed the Solaris ones both on initial loading the pool
cache and subsequent runs. The test package is rather large (5000+ lines), which is used in a
form to display customer details. On Solaris I was typically getting an initial return time of 5
seconds and on windows, typically, 1 second. Even subsequent runs (i.e. cached) the windows
outperformed Solaris. The parameter sizes for the SGA were approx. the same and the file
systems are the conventional method. In both cases the disk configuration is local.
A database is a set of files (data, redo, ctl and so on) where as An instance is a set of processes
(SMON, PMON, DBWR, etc) and a shared memory segment (SGA).
A database may be mounted and opened by many INSTANCES (Parallel Server) concurrently. An
instance may mount and open ANY database -- however it may only open a single database at
any time. There for you need unique (for the set of files).
DBCA does not create instance. It create database (set of files). The instance is only feelings do a
shutdown and goodbye instance and on windows it registers the necessary services that can be
used to start an instance when you want.
A connection is a physical circuit between you and the database. A connection might be one of
many types -- most popular begin DEDICATED server and SHARED server. Zero, one or more
sessions may be established over a given connection to the database as show above with
sqlplus. A process will be used by a session to execute statements. Sometimes there is a one to
one relationship between CONNECTION->SESSION->PROCESS (eg: a normal dedicated server
connection). Sometimes there is a one to many from connection to sessions (eg: like autotrace,
one connection, two sessions, one process). A process does not have to be dedicated to a specific
connection or session however, for example when using shared server (MTS), your SESSION will
grab a process from a pool of processes in order to execute a statement. When the call is over,
that process is released back to the pool of processes.
Same 14 processes...
Fragmentation is that if you have many “small” holes (regions of contiguous free space) that are
too small to be the next extent of any object. These holes of free space resulted from dropping
some object (or truncating them) and the resulting free space cannot be used by any other
object in that tablespace. This is a direct result of using pctincrease that is not zero and having
many weird sized extents (every extents is unique size and shape). In oracle 8i and above we all
are using locally managed tablespace. These would use either uniform sizing or our automatic
allocation scheme. In either case it is almost impossible to get into a situation where you have
unusable free space.
To see if you suffer from fragmentation you can query from DBA_FREE_SPACE (best to do an
alter tablespace to ensure all contiguous made into 1 big free region). You would look any free
space that is smaller then the smallest next extent size for any object in that tablespace. Check
with below query:
Is there a way we can flush out a known data set from the database buffer cache?
No you don’t, in real life; the cache would never be empty. It is true that 10g introduce an alter
system flush buffer_cache, but it is not really worthwhile. Having empty buffer cache is fake, if no
more so than what you are currently doing.
What would be the best approach to benchmark the response time for a particular query?
What is difference between Char and Varchar2 and which is better approach?
A CHAR datatype and VARCHAR2 datatype are stored identically (eg: the word 'WORD' stored in
a CHAR(4) and a varchar2(4) consume exactly the same amount of space on disk, both have
leading byte counts).
The difference between a CHAR and a VARCHAR is that a CHAR(n) will ALWAYS be N bytes long,
it will be blank padded upon insert to ensure this. A varchar2(n) on the other hand will be 1 to N
bytes long, it will NOT be blank padded. Using a CHAR on a varying width field can be a pain due
to the search semantics of CHAR.
Table created.
1 row created.
----------
Hello
SQL>exec :y := 'Hello'
no rows selected
----------
Hello
Notice how when doing the search with a varchar2 variable (almost every tool in the world
uses this type), we have to rpad() it to get a hit. If the field is in fact ALWAYS 10 bytes long, using
a CHAR will not hurt -- HOWEVER, it will not help either.
Rman always shows date in DD-MON-YY format. How to set date format to M/DD/YYYY
HH24:MI:SS in rman ?
You can just set the NLS_DATE_FORMAT before going into RMAN:
In Rman list backup how do i get time column that shows me date and time including
seconds as generally it is showing only date.
Before connecting the rman target set the date format on command prompt:
There is nothing wrong with doing just OS backups. OS backups are just as valid as RMAN
backups. RMAN is a great tool but it is not the only way to do it. Many people still prefer using a
scripting tool of there choice such as perl or ksh to do this.
RMAN is good if you have lots of databases. The catalog it uses remembers lots of details for
you. You don't have as much to think about.
RMAN is good if you do not have good "paper work" skills in place. Using OS backups, it is more
or less upto you to remember where they are, what they are called and so on. You have to do all
of the book keeping RMAN would do.
RMAN provides incremental backups, something you cannot get without RMAN.
RMAN provides tablespace point in time recovery. You can do this without RMAN but you have
to do it by yourself and it can be rather convoluted.
RMAN is more integrated with OEM. If you do OS backups, you'll have to do everything yourself.
With RMAN you may have less scripting to develop, test and maintain.
If you lose rman, you rebuild from the controlfiles of the backed up databases but, you should
not lose the rman catalog using proper techniques of backup itself.
shutdown immediate;
startup mount
connect /
-and-
shutdown immediate
startup mount
connect /
CREATE TABLE new_table as select <do the update "here"> from old_table;
index new_table
etc on new_table
You can do that using parallel query, with nologging on most operations generating very
little redo and no undo at all in a fraction of the time it would take to update the
data.
What is the difference between to back up the current control file and to backup up
control file copy?
If you backup “current control file” you backup control file which is currently open by an
instance where as If you backup “controlfile file copy" you backup the copy of control file which
is created either with SVRMGRL command "alter system backup controlfile to .." or with RMAN
command "copy current controlfile to ...". In the other words, the control file copy is not current
controlfile backup current controlfile creates a BACKUPSET containing controlfile. You don't
have to give the FILENAME where as backup controlfile copy <filename> creates a BACKUPSET
from a copy of controlfile. You
Backup validate works against the backups not against the live database so no impact on the live
database, same for restore validate they do not impact the real thing (it is reading the files there
only).
Is there a way to force rman to use these obsolete backups or once it is marked obsolete?
As per my understanding it is just a report, they are still there until you delete them.
Can I use the same snapshot controlfile to backup multiple databases(one after another)
running on the same server?
This file is only use temporarily like a scratch file. Only one rman session can access the
snapshot controlfile at any time so this would tend to serialize your backups if you do that.
Why does not oracle keep RMAN info after recreating the controlfile?
Creating the new controlfile from scratch how do you expect the create controlfile to "make up"
the missing data? that would be like saying similarly we have drop and recreated my table and
now it is empty similarly here recreating from the scratch means the contents there will be
naturally will be gone. Use the rman catalog to deal this situation. It is just a suggestion.
What is the advantage of using PIPE in rman backups? In what circumstances one would
use PIPE to backup and restore?
It lets 3rd parties (anyone really) build an alternative interface to RMAN as it permits anyone
run {
allocate channel c1 type disk;
debug on;
rman>debug off;
Assuming I have a "FULL" backup of users01.dbf containing employees table that contains
1000 blocks of data. If I truncated employees table and then an incremental level 1
backup of user’s tablespace is taken, will RMAN include 1000 blocks that once contained
data in the incremental backup?
The blocks were not written to the only changes made by the truncate was to the data dictionary
(or file header) so no, it won't see them as changed blocks since they were not changed.
The recovery catalog to be used by Rman should be created in a separate database other than
the target database. The reason is that the target database will be shutdown while datafiles are
restored.
The default is two times one for the actual command, the other for confirmation.
Rman uses the snapshot controlfile as a way to get a read consistent copy of the controlfile, it
uses this to do things like RESYNC the catalog (else the controlfile is a ‘moving target’, constantly
changing and Rman would get blocked and block the database)
Rman currently won't do tape directly, you need a media manager for that, regarding disk and
tape parallel not as far as I know, you would run two backups separately (not sure). May be
trying to maintain duplicate like that could get the desired.
What is the difference between DELETE INPUT and DELETE ALL command in backup?
Generally speaking LOG_ARCHIVE_DEST_n points to two disk drive locations where we archive
the files, when a command is issued through rman to backup archivelogs it uses one of the
location to backup the data. When we specify delete input the location which was backed up will
get deleted, if we specify delete all (all log_archive_dest_n) will get deleted.
With 9.2 and earlier it is not possible to restore a backupset (actually backup pieces) from a
different location to where RMAN has recorded them to be. As a workaround you would have to
create a link using the location of where the backup was originally located. Then when restoring,
RMAN will think everything is the same as it was.
Starting in 10.1 it is possible to catalog the backup pieces in their new location into the
controlfile and recovery catalog. This means they are available for restoration by RMAN without
creating the link.
Report obsolete backup are reported unusable according to the user’s retention policy where as
Report obsolete orphan report the backup that are unusable because they belong to incarnation
of the database that are not direct ancestor of the current incarnation.
2. Switch with ‘alter system switch log file’ until a new log file group is in state current
What is the difference between alter database recover and sql*plus recover command?
ALTER DATABASE recover is useful when you as a user want to control the recovery where as
SQL*PLUS recover command is useful when we prefer automated recovery.
The V$Backup_Set is used to check the backup details when we are not managing Rman catalog
that is the backup information is stored in controlfile where as Rc_Backup_Set is used when we
are using catalog as a central repository to list the backup information.
Can I cancel a script from inside the script? How I cancil a select on Windows client?
Use ctl-c
How to Find the Number of Oracle Instances Running on Windows Machine
How to create an init.ora from the spfile when the database is down?
SQL> shutdown;
When you shutdown the database, how does oracle maintain the user session i.e.of
sysdba?
sys@ORA920> shutdown
You can see you still have your dedicated server. When you connect as sysdba, you fire up
dedicated server that is where it is.
A disk I/O failure was detected on reading the control file. Basically you have to check whether
the control file is available, permissions are right on the control file, spfile/init.ora right to the
right location, if all checks were done still you are getting the error, then from the multiplexed
control file overlay on the corrupted one.
Let us say you have three control files control01.ctl, control02.ctl and control03.ctl and now you
are getting errors on control03.ctl then just copy control01.ctl over to control03.ctl and you
should be all set.
BOTH indicates that the change is made in memory and in the server parameter file. The new
setting takes effect immediately and persists after the database is shut down and started up
again. If a server parameter file was used to start up the database, then BOTH is the default. If a
parameter file was used to start up the database, then MEMORY is the default, as well as the only
scope you can specify.
Login as SYSDBA
cpu_count integer 2
Could you please tell me what are the possible reason for Spfile corruption and Recovery?
It should not be corrupt under normal circumstances, if it were, it would be a bug or failure of
some component in your system. It could be a file system error or could be a bug.
a) Your alert log has the non-default parameters in it from your last restart.
c) strings spfile.ora > init$ORACLE_SID.ora - and then edit the resulting file to clean it up would
be options.
In case Revoke CREATE TABLE Privilege from an USER giving ORA-01952. What is the
issue? How to do in that case?
This is because this privilege is not assigned to this user directly rather it was assigned through
role “CONNECT” If you remove connect role from the user then you will not be able to create
session (Connect) to database. So basically we have to Revoke the CONNECT Role and Grant
other than create table privilege to this user.
Only before image of data is stored in the UNDO segments. If transaction is rolled back
information from UNDO is applied to restore original datafile. UNDO is never multiplexed.
We can add or remove Oracle Service using oradim which is available in ORACLE_HOME/bin
Why ORA-28000: the account is locked? What you will do in that case?
The Oracle 10g default is to lock an account after 10 bad password attempts and giving ORA-
28000: the account is locked. In that case one of the solutions is increase default limit of the login
attempts.
Consider the situation Buffer Cache of the database is 300MB. One SQL gave the Physical read as
100. I increased as 400MB and now the same SQL giving the Physical read value is 0
At least 2 redo groups are required for a Oracle database to be working normally.
My spfile is corrupt and now I cannot start my database running on my laptop. Is there a way to
build spfile again?
$ cd $ORACLE_HOME/dbs
edit the temp_pfile.ora, clean it up if there is anything "wrong" with it and then
SQL> shutdown
SQL> startup
On windows -- just try editing the spfile [do not try with the prod db first try to check on test db. It
can be dangerous], create a pfile from it. save it, and do the same or if you got problem you can
startup the db from the command line using sqlplus create a pfile, do a manual startup (start the
oracle service, then use sqlplus to start the database)
What is a fractured block? What happens when you restore a file containing fractured
block?
A block in which the header and footer are not consistent at a given SCN. In a user-managed
backup, an operating system utility can back up a datafile at the same time that DBWR is
updating the file. It is possible for the operating system utility to read a block in a half-updated
state, so that the block that is copied to the backup media is updated in its first half, while the
second half contains older data. In this case, the block is fractured.
For non-RMAN backups, the ALTER TABLESPACE ... BEGIN BACKUP or ALTER DATABASE BEGIN
BACKUP command is the solution for the fractured block problem. When a tablespace is in
backup mode, and a change is made to a data block, the database logs a copy of the entire block
image before the change so that the database can reconstruct this block if media recovery finds
that this block was fractured.
The block that the operating system reads can be split, that is, the top of the block is written at
one point in time while the bottom of the block is written at another point in time. If you restore
a file containing a fractured block and Oracle reads the block, then the block is considered a
corrupt.
You recreated the control file by “using backup control file to trace” and using alter
database backup controlfile to ‘location’ command what have you lost in that case?
You lost all of the backup information as using backup controlfile to trace where as using other
ALTER DATABASE BACKUP CONTROLFILE to ‘D:\Backup\control01.ctl’. All backup information
is retained when you take binary control file backup.
is that?
It is an inconsistent backup. If you are in noarchivelog mode ensure that you issue the shutdown
immediate command or startup force is another option that you can issue: startup force-
>shutdown abort; followed by shutdown immediate;
It depends on how you killed the process. If you did and alter system kill session you should be
able to look at the used_ublkblock in v$transaciton to get an estimate for the rollback being
done. If you killed to server process in the OS and PMON is recovering the transaction you can
look at V$FAST_START_TRANSACTIONS view to get the estimate
Create table x(a date, b date, c date);
Select * from sys.dba_unused_col_tabs;
Alter table x drop unused columns;
Alter table x drop column c cascade constraints;
You can use the following query to see the flashback data available.
SELECT to_char(sysdate,'YYYY-MM-DD
HH24:MI') current_time, to_char(f.oldest_flashback_time, 'YYYY-MM-DD
HH24:MI')OLDEST_FLASHBACK_TIME,
(sysdate - f.oldest_flashback_time)*24*60 HIST_MIN FROM v$database
d, V$FLASHBACK_DATABASE_LOG f;
How to get current session id, process id, client process id?
where a.addr = b.paddr
and b.audsid = userenv('sessionid');
V$SESSION.PROCESS – Client process id, on windows it is “:” separated the first # is the process
id on the client and 2nd one is the thread id.
MRC also called as Multiple Reporting Currency in oracle application. Default you have currency
in US Dollars but if your organization operating books are in other currency then you as
application DBA need to enable MRC in applications.
Yes you have to use both in application , for application patches you will use ADPATCH UTILITY
and for applying database patch in application you will use opatch UTILITY.
$ strace -p 1435
A database link is a named object that describes a "path" from one database to another. There
are different types of database link such as: Private database link, public database link &
network database link.
Private database link is created on behalf of a specific user. A private database link can be used
only when the owner of the link specifies a global object name in a SQL statement or in the
definition of the owner's views or procedures.
Public database link is created for the special user group PUBLIC. A public database link can be
used when any user in the associated database specifies a global object name in a SQL statement
or object definition.
Network database link is created and managed by a network domain service. A network
database link can be used when any user of any database in the network specifies a global object
name in a SQL statement or object definition.
select * from v$version;
In Reference to Rman point in time Recovery which scenario is better for you (Until time
or until sequence)?
I am practicing various scenarios for backup and recovery using RMAN. I find until SCN better
than until time, with log_seq in the middle. Until time is still going to use (ultimately) an SCN to
recover, so if you know the SCN it would be preferred if not then time is fine.
If you have forgotten the root password on CentOS then what you will do?
- At the splash screen during boot time, press any key which will take you an interactive menu.
- Then select a Linux version you wish to boot and press “a” to append option to the line this will
bring you to a line with the boot command
- Next at the end of that line type “single” as an option/parameter and then Press “Enter” to exit
and execute the boot this will start the OS with single user mode which allow you to reset the
root password by typing passwd and you can set new password for “root”.
select status, checkpoint_change#, to_char(checkpoint_time, 'DD-MON-YYYY HH24:MI:SS') as ch
eckpoint_time, count(*)
from v$datafile_header
group by status, checkpoint_change#, checkpoint_time
order by status, checkpoint_change#, checkpoint_time;
Check the results of the above query if it returns one and only one row for the online datafiles,
means they are already synchronized in terms of their SCN. Otherwise the datafiles are still not
synchronized yet.
You have just restored from backup and do not have any control files. How would you go
about bringing up this database?
If you do not have a control file, you can create one from scratch in SQL*Plus as follows:
1. sqlplus /nolog
2. connect / as sysdba
3. Startup nomount;
4. the either create controlfile or restore it from the backup (if you have)
From more details follow my blog post "Disaster Recovery from the
scratch": http://shahiddba.blogspot.com/2012/05/rman-disaster-recovery-from-scratch.html
Is there any way to find the last record from the table?
select * from employees where rowid in(select max(rowid) from employees);
select * from employees minus select * from employees where rownum < (select count(*) from e
mployees);
SCN
------------
8843525
SQL> select current_scn, dbms_flashback.get_system_change_number from v$database;
--standby case
Statement processed.
Statement processed.
How to find the last time a session performed any activity?
In v$session the column last_call_et has value which tells us the last time (seconds) ago when the
session performed any activity within the database.
select username, floor(last_call_et / 60) "Minutes", status
from v$session
where username is not null order by last_call_et;
How to find parameters that will take into effect for new sessions?
Using the following query one can find the list of parameters that will take info effect for new
sessions if the value of the parameter is changed.
System altered
Note: you may only want to do this on Dev or Test environment as it would affect performance
on production. I already written on my earlier
post http://shahiddba.blogspot.com/2012/05/dba-interview-questions-with-answers_14.html
in real life; the cache would never be empty
-- displays the status and number of pings for every buffer in the SGA
SQL> select distinct status from v$bh;
STATUS
——---
cr
free
xcur
System altered.
Session altered.
STATUS
——-
Free
By setting the value of 0 to the parameter “job_queue_processes” you can suspend all jobs from
executing in DBA_JOBS. The value of this parameter can be changed without instance restart.
SQL> show parameter job_queue_processes;
Now set the value of the parameter in memory, which will suspend jobs from starting
SQL> select djr.sid, djr.job, djr.failures, djr.this_date, djr.this_sec, dj.what from dba_jobs_running
djr, dba_jobs dj where djr.job = dj.job;
GSM stands for Generic Service Management Framework. Oracle E-Business Suite consist of
various compoennts like Forms, Reports, Web Server, Workflow, Concurrent Manager. Earlier
each service used to start at their own but managing these services (given that) they can be on
various machines distributed across network. So Generic Service Management is extension of
Concurrent Processing which manages all your services , provide fault tolerance (If some service
is down ICM through FNDSM and other processes will try to start it even on remote server) With
GSM all services are centrally managed via this Framework.
In a situation when you want to know which was the last query fired by the user. How to
check?
Select S.USERNAME||'('||s.sid||')-'||s.osuser UNAME
,s.sid||'/'||s.serial# sid,s.status "Status",p.spid,sql_text sqltext
from v$sqltext_with_newlines t,V$SESSION s , v$process p
where t.address =s.sql_address and p.addr=s.paddr(+) and t.hash_value = s.sql_hash_value
order by s.sid,t.piece;
Yes, one can copy or FTP the Oracle Software between similar machines. Look at the following
example:
# use tar to copy files and directorys with permissions and ownership
cd /new/oracle/dir/
NOTE: Remember to relink the Intelligent Agent on the new machine to prevent messages like
“Encryption key supplied is not the one used to encrypt file”:
cd /new/oracle/dir/
cd network/lib
A single transaction can have multiple deletes and a single SCN number identifying all of
these deletes. What if I want to flash back only a single individual delete?
You would flash back to the SYSTEM (not your transactions) SCN at that point in time. The
SYSTEM has an SCN, your transaction has an SCN. You care about the SYSTEM SCN with
flashback, not your transactions SCN.
Are flash back queries useful for the developer or the DBA both? How can I as a developer
and DBA get to know the SCN number of a transaction?
Oracle Flashback is a tool is useful for both either DBA and Developer. If you deleted data
accidently then either DBA or Developer both can flashback, recover and fix this problem. As a
developer you can use "dbms_flashback.get_system_change_number" to returns the current
system SCN and as DBA you can use Log Miner utility to to look back in time at various events to
find SCN's as well.
After Performing DML operation you are using flashback query to retun back your
committed data can you use flashback concept after Truncating any data?
In version 9i, Flashback is limited to Data Manipulation Language (DML) commands such as
SELECT,INSERT, UPDATE, and DELETE. Truncate doesn't generate any undo for the table
truncate just cuts it all loses where as delete puts the deleted data into undo. Flashback query
works on undo.
It depends on how you killed the process. If you did and alter system kill session you should be
able to look at the used_ublkblock in v$transaciton to get an estimate for the rollback being
done. If you killed to server process in the OS and PMON is recovering the transaction you can
look at V$FAST_START_TRANSACTIONS view to get the estimate
Create table x(a date, b date, c date);
Now to drop column B:
Select * from sys.dba_unused_col_tabs;
Alter table x drop unused columns;
Alter table x drop column c cascade constraints;
You can use the following query to see the flashback data available.
SELECT to_char(sysdate,'YYYY-MM-DD
HH24:MI') current_time, to_char(f.oldest_flashback_time, 'YYYY-MM-DD
HH24:MI')OLDEST_FLASHBACK_TIME,
(sysdate - f.oldest_flashback_time)*24*60 HIST_MIN FROM v$database
d, V$FLASHBACK_DATABASE_LOG f;
How to get current session id, process id, client process id?
where a.addr = b.paddr
and b.audsid = userenv('sessionid');
V$SESSION.PROCESS – Client process id, on windows it is “:” separated the first # is the process
id on the client and 2nd one is the thread id.
MRC also called as Multiple Reporting Currency in oracle application. Default you have currency
in US Dollars but if your organization operating books are in other currency then you as
application DBA need to enable MRC in applications.
Yes you have to use both in application , for application patches you will use ADPATCH UTILITY
and for applying database patch in application you will use opatch UTILITY.
Do you have idea how to trace a running process on Linux?
Using strace you can trace the system calls being executed by a running process
$ strace -p 1435
A database link is a named object that describes a "path" from one database to another. There
are different types of database link such as: Private database link, public database link &
network database link.
Private database link is created on behalf of a specific user. A private database link can be used
only when the owner of the link specifies a global object name in a SQL statement or in the
definition of the owner's views or procedures.
Public database link is created for the special user group PUBLIC. A public database link can be
used when any user in the associated database specifies a global object name in a SQL statement
or object definition.
Network database link is created and managed by a network domain service. A network
database link can be used when any user of any database in the network specifies a global object
name in a SQL statement or object definition.
select * from v$version;
In Reference to Rman point in time Recovery which scenario is better for you (Until time
or until sequence)?
I am practicing various scenarios for backup and recovery using RMAN. I find until SCN better
than until time, with log_seq in the middle. Until time is still going to use (ultimately) an SCN to
recover, so if you know the SCN it would be preferred if not then time is fine.
If you have forgotten the root password on CentOS then what you will do?
- At the splash screen during boot time, press any key which will take you an interactive menu.
- Then select a Linux version you wish to boot and press “a” to append option to the line this will
bring you to a line with the boot command
- Next at the end of that line type “single” as an option/parameter and then Press “Enter” to exit
and execute the boot this will start the OS with single user mode which allow you to reset the
root password by typing passwd and you can set new password for “root”.
select status, checkpoint_change#, to_char(checkpoint_time, 'DD-MON-YYYY HH24:MI:SS') as ch
eckpoint_time, count(*)
from v$datafile_header
group by status, checkpoint_change#, checkpoint_time
order by status, checkpoint_change#, checkpoint_time;
Check the results of the above query if it returns one and only one row for the online datafiles,
means they are already synchronized in terms of their SCN. Otherwise the datafiles are still not
synchronized yet.
You have just restored from backup and do not have any control files. How would you go
about bringing up this database?
If you do not have a control file, you can create one from scratch in SQL*Plus as follows:
1. sqlplus /nolog
2. connect / as sysdba
3. Startup nomount;
4. the either create controlfile or restore it from the backup (if you have)
From more details follow my blog post "Disaster Recovery from the
scratch": http://shahiddba.blogspot.com/2012/05/rman-disaster-recovery-from-scratch.html
Is there any way to find the last record from the table?
select * from employees where rowid in(select max(rowid) from employees);
select * from employees minus select * from employees where rownum < (select count(*) from e
mployees);
SCN
------------
8843525
SQL> select current_scn, dbms_flashback.get_system_change_number from v$database;
--standby case
Statement processed.
Statement processed.
How to find the last time a session performed any activity?
In v$session the column last_call_et has value which tells us the last time (seconds) ago when the
session performed any activity within the database.
select username, floor(last_call_et / 60) "Minutes", status
from v$session
where username is not null order by last_call_et;
How to find parameters that will take into effect for new sessions?
Using the following query one can find the list of parameters that will take info effect for new
sessions if the value of the parameter is changed.
System altered
Note: you may only want to do this on Dev or Test environment as it would affect performance
on production. I already written on my earlier
post http://shahiddba.blogspot.com/2012/05/dba-interview-questions-with-answers_14.html
in real life; the cache would never be empty
-- displays the status and number of pings for every buffer in the SGA
SQL> select distinct status from v$bh;
STATUS
——---
cr
free
xcur
System altered.
Session altered.
STATUS
——-
Free
By setting the value of 0 to the parameter “job_queue_processes” you can suspend all jobs from
executing in DBA_JOBS. The value of this parameter can be changed without instance restart.
SQL> show parameter job_queue_processes;
Now set the value of the parameter in memory, which will suspend jobs from starting
SQL> select djr.sid, djr.job, djr.failures, djr.this_date, djr.this_sec, dj.what from dba_jobs_running
djr, dba_jobs dj where djr.job = dj.job;
GSM stands for Generic Service Management Framework. Oracle E-Business Suite consist of
various compoennts like Forms, Reports, Web Server, Workflow, Concurrent Manager. Earlier
each service used to start at their own but managing these services (given that) they can be on
various machines distributed across network. So Generic Service Management is extension of
Concurrent Processing which manages all your services , provide fault tolerance (If some service
is down ICM through FNDSM and other processes will try to start it even on remote server) With
GSM all services are centrally managed via this Framework.
In a situation when you want to know which was the last query fired by the user. How to
check?
Select S.USERNAME||'('||s.sid||')-'||s.osuser UNAME
,s.sid||'/'||s.serial# sid,s.status "Status",p.spid,sql_text sqltext
from v$sqltext_with_newlines t,V$SESSION s , v$process p
where t.address =s.sql_address and p.addr=s.paddr(+) and t.hash_value = s.sql_hash_value
order by s.sid,t.piece;
Yes, one can copy or FTP the Oracle Software between similar machines. Look at the following
example:
# use tar to copy files and directorys with permissions and ownership
cd /new/oracle/dir/
NOTE: Remember to relink the Intelligent Agent on the new machine to prevent messages like
“Encryption key supplied is not the one used to encrypt file”:
cd /new/oracle/dir/
cd network/lib
A single transaction can have multiple deletes and a single SCN number identifying all of
these deletes. What if I want to flash back only a single individual delete?
You would flash back to the SYSTEM (not your transactions) SCN at that point in time. The
SYSTEM has an SCN, your transaction has an SCN. You care about the SYSTEM SCN with
flashback, not your transactions SCN.
Are flash back queries useful for the developer or the DBA both? How can I as a developer
and DBA get to know the SCN number of a transaction?
Oracle Flashback is a tool is useful for both either DBA and Developer. If you deleted data
accidently then either DBA or Developer both can flashback, recover and fix this problem. As a
developer you can use "dbms_flashback.get_system_change_number" to returns the current
system SCN and as DBA you can use Log Miner utility to to look back in time at various events to
find SCN's as well.
After Performing DML operation you are using flashback query to retun back your
committed data can you use flashback concept after Truncating any data?
In version 9i, Flashback is limited to Data Manipulation Language (DML) commands such as
SELECT,INSERT, UPDATE, and DELETE. Truncate doesn't generate any undo for the table
truncate just cuts it all loses where as delete puts the deleted data into undo. Flashback query
works on undo.