PL SQL Interview Questions
PL SQL Interview Questions
PL SQL Interview Questions
TRUNCATE:
Truncate is a DDL command
We can remove bulk amount of records at a time
We can't rollback the records
Release the space in database
Truncate reset the high water mark
Truncate explicitly commit
DELETE:
Delete is a DML command
We can delete record by record
We can rollback the records
Can’t release the memory in database
Delete can’t reset the water mark
Delete implicitly commit
(OR)
Ans: Differences:
TRUNCATE commits after deleting entire table i.e., cannot be rolled back.
Database triggers do not fire on TRUNCATE DELETE allows the filtered deletion.
Deleted records can be rolled back or committed.Database triggers fire on DELETE.
Difference
Mv is a physical table
Procedure:
Procedure allow the DML statements without any restrictions
Function:
Function not allow the DML statements (If you need to use we can use pragma)
5. What is cursor?
Cursor is private sql area which is used to execute sql statements and store
processing information
The implicit cursor is automatically declared by oracle every time an sql statement
is executed whenever you issue a sql statement, the oracle server opens an area of
memory in which the command is parsed and executed. Every implicit cursor attribute
start with sql%.
An explicit cursor is created and managed by the user. And used for multi row
select statement.
Table: A table is the basic unit of data storage in an Oracle database. The tables
of a database hold all of the user accessible data. Table data is stored in rows
and columns.a
Views: A view is a virtual table. Every view has a query attached to it. (The query
is a SELECT statement that identifies the columns and rows of the table(s) the view
uses.)
- Present the data in a different perspective from that of the base table.
Ans: A Sequence generates a serial list of unique numbers for numerical columns of
a database's tables.
11.What is a synonym?
Ans: A synonym is an alias for a table, view, sequence or program unit.
16.What is a schema?
Ans: The set of objects owned by user account is called the schema.
Ans: Join is a query, which retrieves related columns or rows from multiple tables.
Non-Equi Join - Joining two tables by not 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.
Ans: INSTR (String1, String2 (n, (m)), INSTR returns the position of the m-th
occurrence of the string 2 in string1. The search begins from nth position of
string1.
19.What is difference between CHAR and VARCHAR2? What is the maximum SIZE allowed
for each type?
Ans: CHAR pads blank spaces to the maximum length. VARCHAR2 does not pad blank
spaces. For CHAR the maximum length is 255 and 2000 for VARCHAR2
20.How to access the current value and next value from a sequence?
Ans: Oracle database is comprised of three types of files. One or more datafiles,
two are more redo log files, and one or more control files.
Ans: Delete from emp where rowid not in (Select min(rowid) from emp Groupby
emp_dept)
Ans: The Oracle Engine uses a work area for its internal processing in order to
execute an SQL statement. This work area is private to SQL operation and is called
Cursor.
Types of Cursor:
Implicit Cursor: If the Oracle engine opened a cursor for its internal processing
then it is know as implicit cursor. It is invoked implicitly.
Explicit Cursor: A cursor which is opened for processing data through a PL/SQL
block is know as Explicit Cursor.
Syntax is SQL%ISOPEN
26.What is a tablespace?
Ans: Yes
Ans: SELECT a.emp_name,a.sal FROM emp a WHERE &n - 1= (SELECT COUNT(DISTINCT sal)
FROM emp b WHERE b.sal > a.sal )
Ans: 12 triggers(Oracle).
Ans: ROWID is pseudo column in every table. The physical address of the rows is use
to for the ROWID.IN HEXADECIMAL representation, ROWID is shown as 18 character
string of the following format BBBBBBBBB.RRRR.FFFF (block, row, file) FFFF is the
fileid of the datafile that contains the row. BBBBBBBBB is the address of the
datablock within the datafile that contains the row. RRRR is the ROW NUMBER with
the data block that contains the row. They are unique identifiers for the any row
in a table. They are internally used in the construction of indexes.
Rownum is the sequential number of rows in the result set object.
Ans: By rowid
Ans: A LEFT JOIN will take ALL values from the first declared table and matching
values from the second declared table based on the column the join has been
declared on. An INNER JOIN will take only matching values from both tables
Ans: Use the DECODE function. This function is absolutely brilliant and functions
like a CASE statement, and can be used to return different columns based on the
values of others.
36.What is Dual ?
Ans: The DUAL table is a table with a single row and a single column used where a
table is syntactically required.
Ans: CHAR is fixed length character type at storage level, and that VARCHAR will be
variable length.
Ans: No
39.How will the fetch the last inserted record in any table ?
Ans: select column 1, column 2.... From where rowid = (select max(rowid) from
table);
3. PRIMARY KEY : disallows duplicate values and nulls in a column or set of columns
4. FOREIGN KEY : requires each value in a column or set of columns match a value in
a related table's UNIQUE or PRIMARY KEY.
5. CHECK : disallows values that do not satisfy the logical expression of the
constrain
A referential integrity constraint requires that for each row of a table, the value
in the foreign key matches a value in a parent key.
Ans: Group by clause tells oracle to group rows based on distinct values that
exists for specified columns. The group by clause creates a data set , containing
several sets of records grouped together based on condition.
Having Clause: Having clause can be used with GROUP BY clause. Having imposes a
condition on the group by clause which further filters the group created by the
GROUP BY clause. Select ename,empno From Empl Group by empno having empno > 10;
Ans: Locks are mechanisms intended to prevent destructive interaction between users
accessing ORACLE data. ORACLE uses locks to control concurrent access to data.
Locks are used to achieve two important database goals : Consistency : Ensures that
the data a user is viewing or changing is not changed (by other users) until the
user is finished with the data. Integrity : Ensures that the database's data and
structures reflect all changes made to them in the correct sequence.
Types of Locks :
4. Distributed Locks
Data Locks : Row Level and Table Level Row Level : Exclusive Locks Table Level
Dictionary Locks :
Ans: Foreign key: A foreign key is one or more columns whose values are based on
the primary or candidate key values from another table. Unique key can be null;
Primary key cannot be null.
1. A TRUNCATE statement does not generate any rollback information and it commits
immediately; it is a DDL statement and cannot be rolled back.
2. A TRUNCATE statement does not affect any structures associated with the table
being truncated (constraints and triggers) or authorizations (grants).
3. A TRUNCATE statement also specifies whether space currently allocated for the
table is returned to the containing tablespace after truncation.
4. As a TRUNCATE statement deletes rows from a table (or clustered table), triggers
associated with the table are not fired.
5. Also, a TRUNCATE statement does not generate any audit information corresponding
to DELETE statements if auditing is enabled. Instead, a single audit record is
generated for the TRUNCATE statement being issued.
1. Create a cursor
3. Describe Results
4. Defining outputs
Ans: Parsing : Parsing is the process of: 1. Translating a SQL statement, verifying
it to be a valid statement 2. Performing data dictionary lookups to check table and
column definitions 3. Acquiring parse locks on required objects so that their
definitions do not change during the statement's parsing 4. Checking privileges to
access referenced schema objects 5. Determining the execution plan to be used when
executing the statement 6. Loading it into a shared SQL area 7. For distributed
statements, routing all or part of the statement to remote nodes that contain
referenced data
Ans: Hints are suggestions that you give the optimizer for optimizing a SQL
statement. Hints allow you to make decisions usually made by the optimizer.
TYPES OF HINTS :
ALL_ROWS : The ALL_ROWS hint explicitly chooses the cost-based approach to optimize
a statement block with a goal of best throughput.
FIRST_ROWS : The FIRST_ROWS hint explicitly chooses the cost-based approach to
optimize a statement block with a goal of best response time.
FULL : The FULL hint explicitly chooses a full table scan for the specified table.
ROWID : The ROWID hint explicitly chooses a table scan by ROWID for the specified
table.
CLUSTER : The CLUSTER hint explicitly chooses a cluster scan to access the
specified table.
HASH : The HASH hint explicitly chooses a hash scan to access the specified table.
INDEX : The INDEX hint explicitly chooses an index scan for the specified table.
AND_EQUAL: The AND_EQUAL hint explicitly chooses an execution plan that uses an
access path that merges the scans on several single-column indexes. (You can
specify multiple indexes through this hint) INDEX_ASC: The INDEX_ASC hint
explicitly chooses an index scan for the specified table. If the statement uses an
index range scan, ORACLE scans the index entries in ascending order of their
indexed values.
INDEX_DESC: The INDEX_DESC hint explicitly chooses an index scan for the specified
table. If the statement uses an index range scan, ORACLE scans the index entries in
descending order of their indexed values.
ORDERED : The ORDERED hint causes ORACLE to join tables in the order in which they
appear in the FROM clause.
USE_NL : The USE_NL hint causes ORACLE to join each specified table to another row
source with a nested loops join using the specified table as the inner table.
USE_MERGE : The USE_MERGE hint causes ORACLE to join each specified table with
another row source with a sort-merge join.
Ans: EXCEPTION_INIT Pragma : To handle unnamed internal exceptions, you must use
the OTHERS handler or the pragma EXCEPTION_INIT. A "pragma" is a compiler
directive, which can be thought of as a parenthetical remark to the compiler.
Pragmas (also called "pseudoinstructions") are processed at compile time, not at
run time. They do not affect the meaning of a program; they simply convey
information to the compiler. The predefined pragma EXCEPTION_INIT tells the PL/SQL
compiler to associate an exception name with an Oracle error number. That allows
you to refer to any internal exception by name and to write a specific handler for
it. You code the pragma EXCEPTION_INIT in the declarative part of a PL/SQL block,
subprogram, or package
Ans: JSP Query : The JSP Query is a standard query for number to words conversion,
used especially for converting amount in number into equivalent amount in words.
The query is as follows : Select to_char ( to_date ( ‘&no’, ‘J’ ), ‘JSP’ ) words
from dual; For eg : Select to_char ( to_date ( '23949','j' ), 'JSP' ) "words" from
dual; The value that can pass to &no cannot exceed 7 digits.
Ans: Physical: Data files, Redo Log files, Control file. Logical : Tables, Views,
Tablespaces, etc.
Ans: 254(Oracle)
Ans: No
Ans: 3
Ans: No
Ans: Alias is temporary and used with one query. Synonym is permanent and not used
as alias.
Ans: 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.
Ans: Throughout its operation, ORACLE maintains a set of "virtual" tables that
record current database activity. These tables are called Dynamic performance
tables. Because dynamic performance tables are not true tables, they should not be
accessed by most users. However, database administrators can query these tables and
can create views on the tables and grant access to those views to other users. The
dynamic performance tables are owned by SYS and their names all begin with V_$.
Views are created on these tables, and then synonyms are created for the views. The
synonym names begin with V$.
59.What is Savepoint ?
Ans: Savepoints are intermediate markers that can be declared in long transactions
that contain many SQL statements. By using savepoints, you can arbitrarily mark
your work at any point within a long transaction. This allows you the option of
later rolling back all work performed from the current point in the transaction to
a declared savepoint within the transaction.
60.What is Deadlocks?
Ans: A deadlock is a situation that can occur in multi-user systems that causes
some number of transactions to be unable to continue work. A deadlock can occur
when two or more users are waiting for data locked by each other. It typically
happens when each of two or more users are waiting to access a resource that
another user has already locked. This creates a deadlock situation because each
user is waiting for resources held by the other user. Eg Transaction 1 Time Point
Transaction 2 UPDATE emp 1 UPDATE emp SET sal = sal*1.1 SET sal = 1342 WHERE empno
= 1000; WHERE empno = 2000; UPDATE emp 2 UPDATE emp SET sal = sal*1.1 SET sal =
1342 WHERE empno = 2000; WHERE empno = 1000; ORA-00060 3 deadlock detected while
waiting for resource
61.What is Privilege ?
Ans: Two Phase Commit is a mechanism wherein ORACLE automatically controls and
monitors the commit or rollback of a distributed transaction and maintains the
integrity of the global database. The Phases of the Two-Phase Commit Mechanism :
• Prepare phase : The global co-ordinator (initiating node) asks participants to
prepare (to promise to commit or rollback the transaction, even if there is a
failure).
• Commit phase : If all participants respond to the co-ordinator that they are
prepared, the co-ordinator asks all nodes to commit the transaction; if all
participants cannot prepare, the co-ordinator asks all nodes to roll back the
transaction.
Ans: Snapshots are read-only copies of a master table (or multiple tables) located
on a remote node. A snapshot can be queried, but not updated; only the master table
can be updated. A snapshot is periodically refreshed to reflect changes made to the
master table. A snapshot is a full copy of a table or a subset of a table that
reflects a recent state of the master table. A snapshot is defined by a distributed
query that references one or more master tables, view, or other snapshots. Simple
vs. Complex Snapshots : Each row in a simple snapshot is based on a single row in a
single remote table. Therefore, a simple snapshot's defining query has no GROUP BY
or CONNECT BY clauses, or subqueries, joins, or set operations. If a snapshot's
defining query contains any of these clauses or operations, it is referred to as a
complex snapshot. Internals of Snapshot Creation: When a snapshot is created,
several operations are performed internally by ORACLE: • ORACLE (at the snapshot
node) creates a table to store the rows retrieved by the snapshot's defining query;
this is the snapshot's base table. • ORACLE creates a read-only view on the SNAP$
table (base table) for queries issued against the snapshot. • ORACLE creates a
second local view on the remote master table. It uses this view when it refreshes
the snapshot. • Additionally, if the snapshot is a simple snapshot, ORACLE creates
an index on the SNAP$ table. All of these internal objects are created in the
schema of the snapshot. Do not alter, change data in, or delete these objects
manually.
Ans: A REF CURSOR is basically a data type. A variable created based on such a data
type is generally called a cursor variable. A cursor variable can be associated
with different queries at run-time. The primary advantage of using cursor variables
is their capability to pass result sets between sub programs (like stored
procedures, functions, packages etc.).
Ans: Row chaining occurs when a VARCHAR2 value is updated and the length of the new
value is longer than the old value and won’t 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.
Ans: 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. An
instantaneous reading gives more valuable data since it will tell you what your
instance is doing for the time it was generated over.
68.What is a mutating table error and how can you get around it?
Ans: This happens with triggers. It occurs because the trigger is trying to update
a row it is currently using. The usual fix involves either use of views or
temporary tables so the database is selecting from one while updating the other.
69.What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?
Ans: SQLCODE returns the value of the error number for the last error encountered.
The SQLERRM returns the actual error message for the last error encountered. They
can be used in exception handling to report, or, store in an error log table, the
error that occurred in the code. These are especially useful for the WHEN OTHERS
exception.
transactional triggers and user exits, you can build a form to interact with
virtually any data source, including even non-relational databases and flat files.
Calling User Exits When you define transactional triggers to interact with a non-
ORACLE data source, you will usually include a call to a user exit in the
appropriate triggers. The code in your user exit interacts with the non-ORACLE data
source. Once the user exit has performed the appropriate function (as indicated by
the trigger from which it was called), it returns control to Oracle Forms for
subsequent processing. For example, a user exit called from an On-Fetch trigger
might be responsible for retrieving the appropriate number of records from the non-
ORACLE data source. Once the records are retrieved, Oracle Forms takes over the
display and management of those records in the form interface, just as it would if
the records had been fetched from an ORACLE database. Uses for Transactional
Triggers • Transactional triggers, except for the commit triggers, are primarily
intended to access certain data sources other than Oracle. • The logon and logoff
transactional triggers can also be used with Oracle databases to change connections
at run time.
71.What is Autonomous transaction ? Where do we use it?
Ans: When a statement in a trigger body causes another trigger to be fired, the
triggers are said to be cascading. Max = 32
Ans: The & operator means that the PL SQL block requires user input for a variable.
The && operator means that the value of this variable should be the same as
inputted by the user previously for this same variable.
77.If all the values from a cursor have been fetched and another fetch is issued,
the output will be?
Ans: PL/SQL requires that you declare an identifier before using it. Therefore, you
must declare a subprogram before calling it. This declaration at the start of a
subprogram is called forward declaration. A forward declaration consists of a
subprogram specification terminated by a semicolon.
Ans: %ROWTYPE allows you to associate a variable with an entire table row. The
%TYPE associates a variable with a single column type.
83.What is RAISE_APPLICATION_ERROR ?