Thursday 22 November 2012

Oracle Questions


What is a Synonym ?
A synonym is an alias for a table, view, sequence or program unit.
What is a Sequence ?
A sequence generates a serial list of unique numbers for numerical columns of a database's tables.
What is a Segment ?
A segment is a set of extents allocated for a certain logical structure.
What is schema?
A schema is collection of database objects of a User.
Describe Referential Integrity ?
A rule defined on a column (or set of columns) in one table that allows the insert or update of a row only if the value for the column or set of columns (the dependent value) matches a value in a column of a related table (the referenced value). It also specifies the type of data manipulation allowed on referenced data and the action to be performed on dependent data as a result of any action on referenced data.
What is Hash Cluster ?
A row is stored in a hash cluster based on the result of applying a hash function to the row's cluster key value. All rows with the same hash key value are stores together on disk.
What is a Private Synonyms ?
A Private Synonyms can be accessed only by the owner.
What is Database Link ?
A database link is a named object that describes a "path" from one database to another.
What is index cluster?
A cluster with an index on the cluster key.
What is hash cluster?
A row is stored in a hash cluster based on the result of applying a hash function to the row's cluster key value. All rows with the same hash key value are stores together on disk.
When can hash cluster used?
Hash clusters are better choice when a table is often queried with equality queries. For such queries the specified cluster key value is hashed. The resulting hash key value points directly to the area on disk that stores the specified rows.
When can hash cluster used?
Hash clusters are better choice when a table is often queried with equality queries. For such queries the specified cluster key value is hashed. The resulting hash key value points directly to the area on disk that stores the specified rows.
What are the types of database links?
Private database link, public database link & network database link.
What is private 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.
What is public database link?
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.
What is network database link?
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.
What is data block?
Oracle database's data is stored in data blocks. One data block corresponds to a specific number of bytes of physical database space on disk.
How to define data block size?
A data block size is specified for each Oracle database when the database is created. A database users and allocated free database space in Oracle data blocks. Block size is specified in init.ora file and cannot be changed latter.
What is row chaining?
In circumstances, all of the data for a row in a table may not be able to fit in the same data block. When this occurs, the data for the row is stored in a chain of data block (one or more) reserved for that segment.
What is an extent?
An extent is a specific number of contiguous data blocks, obtained in a single allocation and used to store a specific type of information.
What are the different types of segments?
Data segment, index segment, rollback segment and temporary segment.
What is a data segment?
Each non-clustered table has a data segment. All of the table's data is stored in the extents of its data segment. Each cluster has a data segment. The data of every table in the cluster is stored in the cluster's data segment.
What is an index segment?
Each index has an index segment that stores all of its data.
What is rollback segment?
A database contains one or more rollback segments to temporarily store "undo" information.
What are the uses of rollback segment?
To generate read-consistent database information during database recovery and to rollback uncommitted transactions by the users.
What is a temporary segment?
Temporary segments are created by Oracle when a SQL statement needs a temporary work area to complete execution. When the statement finishes execution, the temporary segment extents are released to the system for future use.
What is a datafile?
Every Oracle database has one or more physical data files. A database's data files contain all the database data. The data of logical database structures such as tables and indexes is physically stored in the data files allocated for a database.
What are the characteristics of data files?
A data file can be associated with only one database. Once created a data file can't change size. One or more data files form a logical unit of database storage called a tablespace.
What is a redo log?
The set of redo log files for a database is collectively known as the database redo log.
What is the function of redo log?
The primary function of the redo log is to record all changes made to data.
What is the use of redo log information?
The information in a redo log file is used only to recover the database from a system or media failure prevents database data from being written to a database's data files.
What does a control file contains?
- Database name
- Names and locations of a database's files and redolog files.
- Time stamp of database creation.
What is the use of control file?
When an instance of an Oracle database is started, its control file is used to identify the database and redo log files that must be opened for database operation to proceed. It is also used in database recovery.
Is it possible to split the print reviewer into more than one region?
Yes
Is it possible to center an object horizontally in a repeating frame that has a variable horizontal size?
Yes
For a field in a repeating frame, can the source come from the column which does not exist in the data group which forms the base for the frame?
Yes
Can a field be used in a report without it appearing in any data group?
Yes
The join defined by the default data link is an outer join yes or no?
Yes
Can a formula column referred to columns in higher group?
Yes
Can a formula column be obtained through a select statement?
Yes
Is it possible to insert comments into sql statements return in the data model editor?
Yes
Is it possible to disable the parameter from while running the report?
Yes
When a form is invoked with call_form, Does oracle forms issues a save point?
Yes
Explain the difference between a hot backup and a cold backup and the benefits associated with each.
A hot backup is basically taking a backup of the database while it is still up and running and it must be in archive log mode. A cold backup is taking a backup of the database while it is shut down and does not require being in archive log mode. The benefit of taking a hot backup is that the database is still available for use while the backup is occurring and you can recover the database to any point in time. The benefit of taking a cold backup is that it is typically easier to administer the backup and recovery process. In addition, since you are taking cold backups the database does not require being in archive log mode and thus there will be a slight performance gain as the database is not cutting archive logs to disk.
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.
How do you switch from an init.ora file to a spfile?
Issue the create spfile from pfile command.
Explain the difference between a data block, an extent and a segment.
A data block is the smallest unit of logical storage for a database object. As objects grow they take chunks of additional storage that are composed of contiguous data blocks. These groupings of contiguous data blocks are called extents. All the extents that an object takes when grouped together are considered the segment of the database object.
Give two examples of how you might determine the structure of the table DEPT.
Use the describe command or use the dbms_metadata.get_ddl package.
Where would you look for errors from the database engine?
In the alert log.
Compare and contrast TRUNCATE and DELETE for a table.
Both the truncate and delete command have the desired outcome of getting rid of all the rows in a table. The difference between the two is that the truncate command is a DDL operation and just moves the high water mark and produces a now rollback. The delete command, on the other hand, is a DML operation, which will produce a rollback and thus take longer to complete.
Give the reasoning behind using an index.
Faster access to data blocks in a table.
Give the two types of tables involved in producing a star schema and the type of data they hold.
Fact tables and dimension tables. A fact table contains measurements while dimension tables will contain data that will help describe the fact tables.
What type of index should you use on a fact table?
A Bitmap index.
Give two examples of referential integrity constraints.
A primary key and a foreign key.
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, enable the foreign key constraint.
Explain the difference between ARCHIVELOG mode and NOARCHIVELOG mode and the benefits and disadvantages to each.
ARCHIVELOG mode is a mode that you can put the database in for creating a backup of all transactions that have occurred in the database so that you can recover to any point in time. NOARCHIVELOG mode is basically the absence of ARCHIVELOG mode and has the disadvantage of not being able to recover to any point in time. NOARCHIVELOG mode does have the advantage of not having to write transactions to an archive log and thus increases the performance of the database slightly.
What command would you use to create a backup control file?
Alter database backup control file to trace.
Give the stages of instance startup to a usable state where normal users may access it.
STARTUP NOMOUNT - Instance startup
STARTUP MOUNT - The database is mounted
STARTUP OPEN - The database is opened
What column differentiates the V$ views to the GV$ views and how?
The INST_ID column which indicates the instance in a RAC environment the information came from.
How would you go about generating an EXPLAIN plan?
Create a plan table with utlxplan.sql.
Use the explain plan set statement_id = 'tst1' into plan_table for a SQL statement
Look at the explain plan with utlxplp.sql or utlxpls.sql
How would you go about increasing the buffer cache hit ratio?
Use the buffer cache advisory over a given workload and then query the v$db_cache_advice table. If a change was necessary then I would use the alter system set db_cache_size command.
Explain an ORA-01555
You get this error when you get a snapshot too old within rollback. It can usually be solved by increasing the undo retention or increasing the size of rollbacks. You should also look at the logic involved in the application getting the error message.
Explain the difference between $ORACLE_HOME and $ORACLE_BASE.
ORACLE_BASE is the root directory for oracle. ORACLE_HOME located beneath ORACLE_BASE is where the oracle products reside.
How would you determine the time zone under which a database was operating?
select DBTIMEZONE from dual;
Explain the use of setting GLOBAL_NAMES equal to TRUE.
Setting GLOBAL_NAMES dictates how you might connect to a database. This variable is either TRUE or FALSE and if it is set to TRUE it enforces database links to have the same name as the remote database to which they are linking.
What command would you use to encrypt a PL/SQL application?
WRAP
Explain the difference between a FUNCTION, PROCEDURE and PACKAGE.
A function and procedure are the same in that they are intended to be a collection of PL/SQL code that carries a single task. While a procedure does not have to return any values to the calling application, a function will return a single value. A package on the other hand is a collection of functions and procedures that are grouped together based on their commonality to a business function or application.
Explain the use of table functions.
Table functions are designed to return a set of rows through PL/SQL logic but are intended to be used as a normal table or view in a SQL statement. They are also used to pipeline information in an ETL process.
Name three advisory statistics you can collect.
Buffer Cache Advice, Segment Level Statistics, & Timed Statistics
Where in the Oracle directory tree structure are audit traces placed?
In unix $ORACLE_HOME/rdbms/audit, in Windows the event viewer
Explain materialized views and how they are used.
Materialized views are objects that are reduced sets of information that have been summarized, grouped, or aggregated from base tables. They are typically used in data warehouse or decision support systems.
When a user process fails, what background process cleans up after it?
PMON
What background process refreshes materialized views?
The Job Queue Processes.
How would you determine what sessions are connected and what resources they are waiting for?
Use of V$SESSION and V$SESSION_WAIT
Describe what redo logs are.
Redo logs are logical and physical structures that are designed to hold all the changes made to a database and are intended to aid in the recovery of a database.
How would you force a log switch?
ALTER SYSTEM SWITCH LOGFILE;
Give two methods you could use to determine what DDL changes have been made.
You could use Logminer or Streams
What does coalescing a tablespace do?
Coalescing is only valid for dictionary-managed tablespaces and de-fragments space by combining neighboring free extents into large single extents.
What is the difference between a TEMPORARY tablespace and a PERMANENT tablespace?
A temporary tablespace is used for temporary objects such as sort structures while permanent tablespaces are used to store those objects meant to be used as the true objects of the database.
Name a tablespace automatically created when you create a database.
The SYSTEM tablespace.
When creating a user, what permissions must you grant to allow them to connect to the database?
Grant the CONNECT to the user.
How do you add a data file to a tablespace
ALTER TABLESPACE <tablespace_name> ADD DATAFILE <datafile_name> SIZE
How do you resize a data file?
ALTER DATABASE DATAFILE <datafile_name> RESIZE <new_size>;
What view would you use to look at the size of a data file?
DBA_DATA_FILES
What view would you use to determine free space in a tablespace?
DBA_FREE_SPACE
How would you determine who has added a row to a table?
Turn on fine grain auditing for the table.
How can you rebuild an index?
ALTER INDEX <index_name> REBUILD;
Explain what partitioning is and what its benefit is.
Partitioning is a method of taking large tables and indexes and splitting them into smaller, more manageable pieces.
You have just compiled a PL/SQL package but got errors, how would you view the errors?
SHOW ERRORS
How can you gather statistics on a table?
The ANALYZE command.
How can you enable a trace for a session?
Use the DBMS_SESSION.SET_SQL_TRACE or
Use ALTER SESSION SET SQL_TRACE = TRUE;
What is the difference between the SQL*Loader and IMPORT utilities?
These two Oracle utilities are used for loading data into the database. The difference is that the import utility relies on the data being produced by another Oracle utility EXPORT while the SQL*Loader utility allows data to be loaded that has been produced by other utilities from different data sources just so long as it conforms to ASCII formatted or delimited files.
Name two files used for network connection to a database.
TNSNAMES.ORA and SQLNET.ORA
What is the function of Optimizer ?
The goal of the optimizer is to choose the most efficient way to execute a SQL statement.
What is Execution Plan ?
The combinations of the steps the optimizer chooses to execute a statement is called an execution plan.
Can one resize tablespaces and data files? (for DBA)
One can manually increase or decrease the size of a datafile from Oracle 7.2 using the command.
ALTER DATABASE DATAFILE 'filename2' RESIZE 100M;
Because you can change the sizes of datafiles, you can add more space to your database without adding more datafiles. This is beneficial if you are concerned about reaching the maximum number of datafiles allowed in your database.
Manually reducing the sizes of datafiles allows you to reclaim unused space in the database. This is useful for correcting errors in estimations of space requirements.
Also, datafiles can be allowed to automatically extend if more space is required. Look at the following command:
CREATE TABLESPACE pcs_data_ts
DATAFILE 'c:\ora_apps\pcs\pcsdata1.dbf' SIZE 3M
AUTOEXTEND ON NEXT 1M MAXSIZE UNLIMITED
DEFAULT STORAGE (INITIAL 10240
NEXT 10240
MINEXTENTS 1
MAXEXTENTS UNLIMITED
PCTINCREASE 0)
ONLINE
PERMANENT;
What is SAVE POINT ?
For long transactions that contain many SQL statements, intermediate markers or savepoints can be declared which can be used to divide a transaction into smaller parts. This allows the option of later rolling back all work performed from the current point in the transaction to a declared savepoint within the transaction.
What are the values that can be specified for OPTIMIZER MODE Parameter ?
COST and RULE. 

PLSQL interview questions part 2


Question What is PL/SQL ?
PL/SQL is a procedural language that has both interactive SQL and procedural programming language constructs such as iteration, conditional branching.
What are the components of OEM? (for DBA)
Oracle Enterprise Manager (OEM) has the following components:
. Management Server (OMS): Middle tier server that handles communication with the intelligent agents. The OEM Console connects to the management server to monitor and configure the Oracle enterprise.
. Console: This is a graphical interface from where one can schedule jobs, events, and monitor the database. The console can be opened from a Windows workstation, Unix XTerm (oemapp command) or Web browser session (oem_webstage).
. Intelligent Agent (OIA): The OIA runs on the target database and takes care of the execution of jobs and events scheduled through the Console.
What happens if a procedure that updates a column of table X is called in a database trigger of the same table ?
Mutation of table occurs.
Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database Trigger ? Why ?
It is not possible. As triggers are defined for each table, if you use COMMIT of ROLLBACK in a trigger, it affects logical transaction processing.
How many types of database triggers can be specified on a table ? What are they ?
Insert Update Delete
Before Row o.k. o.k. o.k.
After Row o.k. o.k. o.k.
Before Statement o.k. o.k. o.k.
After Statement o.k. o.k. o.k.
If FOR EACH ROW clause is specified, then the trigger for each Row affected by the statement.
If WHEN clause is specified, the trigger fires according to the returned Boolean value.
What are the modes of parameters that can be passed to a procedure ?
IN,OUT,IN-OUT parameters.
Where the Pre_defined_exceptions are stored ?
In the standard package.
Procedures, Functions & Packages ;
Write the order of precedence for validation of a column in a table ?
I. done using Database triggers.
ii. done using Integarity Constraints.?

I & ii.
Give the structure of the function ?
FUNCTION name (argument list .....) Return datatype is
local variable declarations
Begin
executable statements
Exception
execution handlers
End;
Explain how procedures and functions are called in a PL/SQL block ?
Function is called as part of an expression.
sal := calculate_sal ('a822');
procedure is called as a PL/SQL statement
calculate_bonus ('A822');
What are advantages fo Stored Procedures?
Extensibility,Modularity, Reusability, Maintainability and one time compilation.
What is an Exception ? What are types of Exception ?
Exception is the error handling part of PL/SQL block. The types are Predefined and user defined. Some of Predefined exceptions are.
CURSOR_ALREADY_OPEN
DUP_VAL_ON_INDEX
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR
INVALID_NUMBER
LOGON_DENIED
NOT_LOGGED_ON
PROGRAM-ERROR
STORAGE_ERROR
TIMEOUT_ON_RESOURCE
VALUE_ERROR
ZERO_DIVIDE
OTHERS.
What are the PL/SQL Statements used in cursor processing ?
DECLARE CURSOR name, OPEN cursor name, FETCH cursor name INTO or Record types, CLOSE cursor name.
What are the components of a PL/SQL Block ?
Declarative part, Executable part and Exception part.
Datatypes PL/SQL
What is a database trigger ? Name some usages of database trigger ?
Database trigger is stored PL/SQL program unit associated with a specific database table. Usages are Audit data modifications, Log events transparently, Enforce complex business rules Derive column values automatically, Implement complex security authorizations. Maintain replicate tables.
What is a cursor ? Why Cursor is required ?
Cursor is a named private SQL area from where information can be accessed. Cursors are required to process rows individually for queries returning multiple rows.
What is a cursor for loop ?
Cursor for loop implicitly declares %ROWTYPE as loop index, opens a cursor, fetches rows of values from active set into fields in the record and closes when all the records have been processed.
e.g.. FOR emp_rec IN C1 LOOP
salary_total := salary_total +emp_rec sal;
END LOOP;
What will happen after commit statement ?
Cursor C1 is
Select empno,
ename from emp;
Begin
open C1; loop
Fetch C1 into
eno.ename;
Exit When
C1 %notfound;-----
commit;
end loop;
end;
The cursor having query as SELECT .... FOR UPDATE gets closed after COMMIT/ROLLBACK.
The cursor having query as SELECT.... does not get closed even after COMMIT/ROLLBACK.
How packaged procedures and functions are called from the following?
a. Stored procedure or anonymous block
b. an application program such a PRC *C, PRO* COBOL
c. SQL *PLUS??


a. PACKAGE NAME.PROCEDURE NAME (parameters);
variable := PACKAGE NAME.FUNCTION NAME (arguments);
EXEC SQL EXECUTE
b.BEGIN
PACKAGE NAME.PROCEDURE NAME (parameters)
variable := PACKAGE NAME.FUNCTION NAME (arguments);
END;
END EXEC;
c. EXECUTE PACKAGE NAME.PROCEDURE if the procedures does not have any out/in-out parameters. A function can not be called.
What is a stored procedure ?
A stored procedure is a sequence of statements that perform specific function.
What are the components of a PL/SQL block ?
A set of related declarations and procedural statements is called block.
What is difference between a PROCEDURE & FUNCTION ?
A FUNCTION is always returns a value using the return statement.
A PROCEDURE may return one or more values through parameters or may not return at all.
What is difference between a Cursor declared in a procedure and Cursor declared in a package specification ?
A cursor declared in a package specification is global and can be accessed by other procedures or procedures in a package.
A cursor declared in a procedure is local to the procedure that can not be accessed by other procedures.
What are the cursor attributes used in PL/SQL ?
%ISOPEN - to check whether cursor is open or not
% ROWCOUNT - number of rows fetched/updated/deleted.
% FOUND - to check whether cursor has fetched any row. True if rows are fetched.
% NOT FOUND - to check whether cursor has fetched any row. True if no rows are featched.
These attributes are proceeded with SQL for Implicit Cursors and with Cursor name for Explicit Cursors.
What are % TYPE and % ROWTYPE ? What are the advantages of using these over datatypes?
% TYPE provides the data type of a variable or a database column to that variable.
% ROWTYPE provides the record type that represents a entire row of a table or view or columns selected in the cursor.
The advantages are :
I. Need not know about variable's data type
ii. If the database definition of a column in a table changes, the data type of a variable changes accordingly.
What is difference between % ROWTYPE and TYPE RECORD ?
% ROWTYPE is to be used whenever query returns a entire row of a table or view.
TYPE rec RECORD is to be used whenever query returns columns of different table or views and variables.
E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type );
e_rec emp% ROWTYPE
cursor c1 is select empno,deptno from emp;
e_rec c1 %ROWTYPE.
What are the different types of PL/SQL program units that can be defined and stored in ORACLE database ?
Procedures and Functions,Packages and Database Triggers.
What are the advantages of having a Package ?
Increased functionality (for example,global package variables can be declared and used by any proecdure in the package) and performance (for example all objects of the package are parsed compiled, and loaded into memory once)
What are the uses of Database Trigger ?
Database triggers can be used to automatic data generation, audit data modifications, enforce complex Integrity constraints, and customize complex security authorizations.
What is a Procedure ?
A Procedure consist of a set of SQL and PL/SQL statements that are grouped together as a unit to solve a specific problem or perform a set of related tasks.
What is a Package ?
A Package is a collection of related procedures, functions, variables and other package constructs together as a unit in the database.
What is difference between Procedures and Functions ?
A Function returns a value to the caller where as a Procedure does not.
What is Database Trigger ?
A Database Trigger is procedure (set of SQL and PL/SQL statements) that is automatically executed as a result of an insert in, update to, or delete from a table.
Can the default values be assigned to actual parameters?
Yes
Can a primary key contain more than one columns?
Yes
What is an UTL_FILE.What are different procedures and functions associated with it?
UTL_FILE is a package that adds the ability to read and write to operating system files. Procedures associated with it are FCLOSE, FCLOSE_ALL and 5 procedures to output data to a file PUT, PUT_LINE, NEW_LINE, PUTF, FFLUSH.PUT, FFLUSH.PUT_LINE,FFLUSH.NEW_LINE. Functions associated with it are FOPEN, ISOPEN.
What are ORACLE PRECOMPILERS?
Using ORACLE PRECOMPILERS, SQL statements and PL/SQL blocks can be contained inside 3GL programs written in C,C++,COBOL,PASCAL, FORTRAN,PL/1 AND ADA. The Precompilers are known as Pro*C,Pro*Cobol,... This form of PL/SQL is known as embedded pl/sql,the language in which pl/sql is embedded is known as the host language. The prcompiler translates the embedded SQL and pl/sql statements into calls to the precompiler runtime library. The output must be compiled and linked with this library to creator an executable.
Differentiate between TRUNCATE and DELETE?
TRUNCATE deletes much faster than DELETE
TRUNCATE
DELETE
It is a DDL statement
It is a DML statement
It is a one way trip, cannot ROLLBACK
One can Rollback
Doesn't have selective features (where clause)
Has
Doesn't fire database triggers
Does
It requires disabling of referential constraints.
What is difference between a formal and an actual parameter?
The variables declared in the procedure and which are passed, as arguments are called actual, the parameters in the procedure declaration. Actual parameters contain the values that are passed to a procedure and receive results. Formal parameters are the placeholders for the values of actual parameters
What should be the return type for a cursor variable. Can we use a scalar data type as return type?
The return type for a cursor must be a record type.It can be declared explicitly as a user-defined or %ROWTYPE can be used. eg TYPE t_studentsref IS REF CURSOR RETURN students%ROWTYPE
What are different Oracle database objects?
-TABLES
-VIEWS
-INDEXES
-SYNONYMS
-SEQUENCES
-TABLESPACES etc
What is difference between SUBSTR and INSTR?
SUBSTR returns a specified portion of a string eg SUBSTR('BCDEF',4) output BCDE INSTR provides character position in which a pattern is found in a string. eg INSTR('ABC-DC-F','-',2) output 7 (2nd occurence of '-')
Display the number value in Words?
SQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))
from emp;
the output like,
SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))
--------- ----------------------------------------
800 eight hundred
1600 one thousand six hundred
1250 one thousand two hundred fifty
If you want to add some text like, Rs. Three Thousand only.
SQL> select sal "Salary ",
(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))
"Sal in Words" from emp
/
Salary Sal in Words
------- -----------------------------------------------
800 Rs. Eight Hundred only.
1600 Rs. One Thousand Six Hundred only.
1250 Rs. One Thousand Two Hundred Fifty only.
What is difference between SQL and SQL*PLUS?
SQL*PLUS is a command line tool where as SQL and PL/SQL language interface and reporting tool. Its a command line tool that allows user to type SQL commands to be executed directly against an Oracle database. SQL is a language used to query the relational database(DML,DCL,DDL). SQL*PLUS commands are used to format query result, Set options, Edit SQL commands and PL/SQL.
What are various joins used while writing SUBQUERIES?
Self join-Its a join foreign key of a table references the same table. Outer Join--Its a join condition used where One can query all the rows of one of the tables in the join condition even though they don't satisfy the join condition.
Equi-join--Its a join condition that retrieves rows from one or more tables in which one or more columns in one table are equal to one or more columns in the second table.
What a SELECT FOR UPDATE cursor represent.?
SELECT......FROM......FOR......UPDATE[OF column-reference][NOWAIT]
The processing done in a fetch loop modifies the rows that have been retrieved by the cursor. A convenient way of modifying the rows is done by a method with two parts: the FOR UPDATE clause in the cursor declaration, WHERE CURRENT OF CLAUSE in an UPDATE or declaration statement.
What are various privileges that a user can grant to another user?
-SELECT
-CONNECT
-RESOURCES
Display the records between two range?
select rownum, empno, ename from emp where rowid in (select rowid from emp where rownum <=&upto minus select rowid from emp where rownum<&Start);
minvalue.sql Select the Nth lowest value from a table?
select level, min('col_name') from my_table where level = '&n' connect by prior ('col_name') < 'col_name')
group by level;
Example:
Given a table called emp with the following columns:
-- id number
-- name varchar2(20)
-- sal number
--
-- For the second lowest salary:
-- select level, min(sal) from emp
-- where level=2
-- connect by prior sal < sal
-- group by level
What is difference between Rename and Alias?
Rename is a permanent name given to a table or column whereas Alias is a temporary name given to a table or column which do not exist once the SQL statement is executed.
Difference between an implicit & an explicit cursor.?
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.
What is a OUTER JOIN?
Outer Join--Its a join condition used where you can query all the rows of one of the tables in the join condition even though they don’t satisfy the join condition.
What is a cursor?
Oracle uses work area to execute SQL statements and store processing information PL/SQL construct called a cursor lets you name a work area and access its stored information A cursor is a mechanism used to fetch more than one row in a Pl/SQl block.
What is the purpose of a cluster?
Oracle does not allow a user to specifically locate tables, since that is a part of the function of the RDBMS. However, for the purpose of increasing performance, oracle allows a developer to create a CLUSTER. A CLUSTER provides a means for storing data from different tables together for faster retrieval than if the table placement were left to the RDBMS.
What is OCI. What are its uses?
Oracle Call Interface is a method of accesing database from a 3GL program. Uses--No precompiler is required,PL/SQL blocks are executed like other DML statements.
The OCI library provides
--functions to parse SQL statemets
--bind input variables
--bind output variables
--execute statements
--fetch the results
How you open and close a cursor variable. Why it is required?
OPEN cursor variable FOR SELECT...Statement
CLOSE cursor variable In order to associate a cursor variable with a particular SELECT statement OPEN syntax is used. In order to free the resources used for the query CLOSE statement is used.
Display Odd/ Even number of records?
Odd number of records:
select * from emp where (rowid,1) in (select rowid, mod(rownum,2) from emp);
Output:-
1
3
5
Even number of records:
select * from emp where (rowid,0) in (select rowid, mod(rownum,2) from emp)
Output:-
2
4
6
What are various constraints used in SQL?
-NULL
-NOT NULL
-CHECK
-DEFAULT
Can cursor variables be stored in PL/SQL tables. If yes how. If not why?
No, a cursor variable points a row which cannot be stored in a two-dimensional PL/SQL table.
Difference between NO DATA FOUND and %NOTFOUND?
NO DATA FOUND is an exception raised only for the SELECT....INTO statements when the where clause of the querydoes not match any rows. When the where clause of the explicit cursor does not match any rows the %NOTFOUND attribute is set to TRUE instead.
Can you use a commit statement within a database trigger?
No
What WHERE CURRENT OF clause does in a cursor?
LOOP
SELECT num_credits INTO v_numcredits FROM classes
WHERE dept=123 and course=101;
UPDATE students
FHKO;;;;;;;;;SET current_credits=current_credits+v_numcredits
WHERE CURRENT OF X;
There is a string 120000 12 0 .125 , how you will find the position of the decimal place?
INSTR('120000 12 0 .125',1,'.')
output 13
What are different modes of parameters used in functions and procedures?
-IN -OUT -INOUT
How you were passing cursor variables in PL/SQL 2.2?
In PL/SQL 2.2 cursor variables cannot be declared in a package.This is because the storage for a cursor variable has to be allocated using Pro*C or OCI with version 2.2, the only means of passing a cursor variable to a PL/SQL block is via bind variable or a procedure parameter.
When do you use WHERE clause and when do 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.
Difference between procedure and function.?
Functions are named PL/SQL blocks that return a value and can be called with arguments procedure a named block that can be called with parameter. A procedure all is a PL/SQL statement by itself, while a Function call is called as part of an expression.
Which is more faster - IN or EXISTS?
EXISTS is more faster than IN because EXISTS returns a Boolean value whereas IN returns a value.
What is syntax for dropping a procedure and a function .Are these operations possible?
Drop Procedure procedure_name
Drop Function function_name
How will you delete duplicating rows from a base table?
delete from table_name where rowid not in (select max(rowid) from table group by duplicate_values_field_name); or delete duplicate_values_field_name dv from table_name ta where rowid <(select min(rowid) from table_name tb where ta.dv=tb.dv);
Difference between database triggers and form triggers?
-Data base trigger(DBT) fires when a DML operation is performed on a data base table. Form trigger(FT) Fires when user presses a key or navigates between fields on the screen
-Can be row level or statement level No distinction between row level and statement level.
-Can manipulate data stored in Oracle tables via SQL Can manipulate data in Oracle tables as well as variables in forms.
-Can be fired from any session executing the triggering DML statements. Can be fired only from the form that define the trigger.
-Can cause other database triggers to fire. Can cause other database triggers to fire, but not other form triggers.
What is a cursor for loop?
Cursor For Loop is a loop where oracle implicitly declares a loop variable, the loop index that of the same record type as the cursor's record.
How you will avoid duplicating records in a query?
By using DISTINCT
What is a view ?
A view is stored procedure based on one or more tables, it’s a virtual table.
What is difference between UNIQUE and PRIMARY KEY constraints?
A table can have only one PRIMARY KEY whereas there can be any number of UNIQUE keys. The columns that compose PK are automatically define NOT NULL, whereas a column that compose a UNIQUE is not automatically defined to be mandatory must also specify the column is NOT NULL.
What is use of a cursor variable? How it is defined?
A cursor variable is associated with different statements at run time, which can hold different values at run time. Static cursors can only be associated with one run time query. A cursor variable is reference type (like a pointer in C).
Declaring a cursor variable:
TYPE type_name IS REF CURSOR RETURN return_type type_name is the name of the reference type,return_type is a record type indicating the types of the select list that will eventually be returned by the cursor variable.
How do you find the numbert of rows in a Table ?
A bad answer is count them (SELECT COUNT(*) FROM table_name)
A good answer is :-
'By generating SQL to ANALYZE TABLE table_name COUNT STATISTICS by querying Oracle System Catalogues (e.g. USER_TABLES or ALL_TABLES).
The best answer is to refer to the utility which Oracle released which makes it unnecessary to do ANALYZE TABLE for each Table individually.
What is the maximum buffer size that can be specified using the DBMS_OUTPUT.ENABLE function?
1,000,00
What are cursor attributes?
-%ROWCOUNT
-%NOTFOUND
-%FOUND
-%ISOPEN
There is a % sign in one field of a column. What will be the query to find it?
'' Should be used before '%'.
What is ON DELETE CASCADE ?
When ON DELETE CASCADE is specified ORACLE maintains referential integrity by automatically removing dependent foreign key values if a referenced primary or unique key value is removed.
What is the fastest way of accessing a row in a table ?
Using ROWID.CONSTRAINTS
What is difference between TRUNCATE & DELETE ?
TRUNCATE commits after deleting entire table i.e., can not be rolled back. Database triggers do not fire on TRUNCATEDELETE allows the filtered deletion. Deleted records can be rolled back or committed. Database triggers fire on DELETE.
What is a transaction ?
Transaction is logical unit between two commits and commit and rollback.
What are the advantages of VIEW ?
To protect some of the columns of a table from other users.To hide complexity of a query.To hide complexity of calculations.
How will you a activate/deactivate integrity constraints ?
The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE constraint/DISABLE constraint.
Where the integrity constraints are stored in Data Dictionary ?
The integrity constraints are stored in USER_CONSTRAINTS.
What is the Subquery ?
Sub query is a query whose return values are used in filtering conditions of the main query.
How to access the current value and next value from a sequence ? Is it possible to access the current value in a session before accessing next value ?
Sequence name CURRVAL, Sequence name NEXTVAL.It is not possible. Only if you access next value in the session, current value can be accessed.
What are the usage of SAVEPOINTS ?value in a session before accessing next value ?
SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling back part of a transaction. Maximum of five save points are allowed.
What is ROWID ?in a session before accessing next value ?
ROWID is a pseudo column attached to each row of a table. It is 18 character long, blockno, rownumber are the components of ROWID.
Explain Connect by Prior ?in a session before accessing next value ?
Retrieves rows in hierarchical order.e.g. select empno, ename from emp where.
How many LONG columns are allowed in a table ? Is it possible to use LONG columns in WHERE clause or ORDER BY ?
Only one LONG columns is allowed. It is not possible to use LONG column in WHERE or ORDER BY clause.
What is Referential Integrity ?
Maintaining data integrity through a set of rules that restrict the values of one or more columns of the tables based on the values of primary key or unique key of the referenced table.
What is a join ? Explain the different types of joins ?
Join is a query which retrieves related columns or rows from multiple tables.Self Join - Joining the table with itself.Equi Join - Joining two tables by equating two common columns.Non-Equi Join - Joining two tables by equating two common columns.Outer Join - Joining two tables in such a way that query can also retrieve rows that do not have corresponding join value in the other table.
If an unique key constraint on DATE column is created, will it validate the rows that are inserted with SYSDATE ?
It won't, Because SYSDATE format contains time attached with it.


What are snap shots and views
Snapshots are mirror or replicas of tables. Views are built using the columns from one or more tables. The Single Table View can be updated but the view with multi table cannot be updated
What are the OOPS concepts in Oracle.
Oracle does implement the OOPS concepts. The best example is the Property Classes. We can categorize the properties by setting the visual attributes and then attach the property classes for the objects. OOPS supports the concepts of objects and classes and we can consider the property classes as classes and the items as objects
What is the difference between candidate key, unique key and primary key
Candidate keys are the columns in the table that could be the primary keys and the primary key is the key that has been selected to identify the rows. Unique key is also useful for identifying the distinct rows in the table.)
What is concurrency
Concurrency is allowing simultaneous access of same data by different users. Locks useful for accesing the database are
a) Exclusive
The exclusive lock is useful for locking the row when an insert,update or delete is being done.This lock should not be applied when we do only select from the row.
b) Share lock
We can do the table as Share_Lock as many share_locks can be put on the same resource.
Previleges and Grants
Previleges are the right to execute a particulare type of SQL statements. e.g :: Right to Connect, Right to create, Right to resource Grants are given to the objects so that the object might be accessed accordingly.The grant has to be given by the owner of the object
Table Space,Data Files,Parameter File, Control Files
Table Space :: The table space is useful for storing the data in the database.When a database is created two table spaces are created.
a) System Table space :: This data file stores all the tables related to the system and dba tables
b) User Table space :: This data file stores all the user related tables
We should have seperate table spaces for storing the tables and indexes so that the access is fast.
Data Files :: Every Oracle Data Base has one or more physical data files.They store the data for the database.Every datafile is associated with only one database.Once the Data file is created the size cannot change.To increase the size of the database to store more data we have to add data file.
Parameter Files :: Parameter file is needed to start an instance.A parameter file contains the list of instance configuration parameters e.g.::
db_block_buffers = 500
db_name = ORA7
db_domain = u.s.acme lang
Control Files :: Control files record the physical structure of the data files and redo log files
They contain the Db name, name and location of dbs, data files ,redo log files and time stamp.
Physical Storage of the Data
The finest level of granularity of the data base are the data blocks.
Data Block :: One Data Block correspond to specific number of physical database space
Extent :: Extent is the number of specific number of contigious data blocks.
Segments :: Set of Extents allocated for Extents. There are three types of Segments
a) Data Segment :: Non Clustered Table has data segment data of every table is stored in cluster data segment
b) Index Segment :: Each Index has index segment that stores data
c) Roll Back Segment :: Temporarily store 'undo' information
What are the Pct Free and Pct Used
Pct Free is used to denote the percentage of the free space that is to be left when creating a table. Similarly Pct Used is used to denote the percentage of the used space that is to be used when creating a table
eg.:: Pctfree 20, Pctused 40
What is Row Chaining
The data of a row in a table may not be able to fit the same data block.Data for row is stored in a chain of data blocks .
What is a 2 Phase Commit
Two Phase commit is used in distributed data base systems. This is useful to maintain the integrity of the database so that all the users see the same values. It contains DML statements or Remote Procedural calls that reference a remote object. There are basically 2 phases in a 2 phase commit.
a) Prepare Phase :: Global coordinator asks participants to prepare
b) Commit Phase :: Commit all participants to coordinator to Prepared, Read only or abort Reply
What is the difference between deleting and truncating of tables
Deleting a table will not remove the rows from the table but entry is there in the database dictionary and it can be retrieved But truncating a table deletes it completely and it cannot be retrieved.
What are mutating tables
When a table is in state of transition it is said to be mutating. eg :: If a row has been deleted then the table is said to be mutating and no operations can be done on the table except select.
What are Codd Rules
Codd Rules describe the ideal nature of a RDBMS. No RDBMS satisfies all the 12 codd rules and Oracle Satisfies 11 of the 12 rules and is the only Rdbms to satisfy the maximum number of rules.
What is Normalisation
Normalisation is the process of organising the tables to remove the redundancy.There are mainly 5 Normalisation rules.
a) 1 Normal Form :: A table is said to be in 1st Normal Form when the attributes are atomic
b) 2 Normal Form :: A table is said to be in 2nd Normal Form when all the candidate keys are dependant on the primary key
c) 3rd Normal Form :: A table is said to be third Normal form when it is not dependant transitively
What is the Difference between a post query and a pre query
A post query will fire for every row that is fetched but the pre query will fire only once.
Deleting the Duplicate rows in the table
We can delete the duplicate rows in the table by using the Rowid
Can U disable database trigger? How?
Yes. With respect to table
ALTER TABLE TABLE
[[ DISABLE all_trigger ]]
What is pseudo columns ? Name them?
A pseudocolumn behaves like a table column, but is not actually stored in the table. You can select from pseudocolumns, but you cannot insert, update, or delete their values. This section describes these pseudocolumns:
* CURRVAL
* NEXTVAL
* LEVEL
* ROWID
* ROWNUM
How many columns can table have?
The number of columns in a table can range from 1 to 254.
Is space acquired in blocks or extents ?
In extents .
What is clustered index?
In an indexed cluster, rows are stored together based on their cluster key values . Can not applied for HASH.
What are the datatypes supported By oracle (INTERNAL)?
Varchar2, Number,Char , MLSLABEL.
What are attributes of cursor?
%FOUND , %NOTFOUND , %ISOPEN,%ROWCOUNT
Can you use select in FROM clause of SQL select ?
Yes.