InterviewQA SQL-PLSQLQA PDF
InterviewQA SQL-PLSQLQA PDF
Ans: Normalization is the process of organizing the tables to remove the redundancy. There are mainly 5 Normalization
rules.
1st Normal Form: A table is said to be in 1st normal form when the attributes are atomic and there is no repeating groups
2nd Normal Form: A table is said to be in 2nd Normal Form when it is in 1st normal form and all the non-key columns are
functionally dependant on the primary key. .
3rd Normal Form: A table is said to be in 3rd Normal form when it is in 2nd normal form and all non key attributes not
dependant transitively.
4th Normal Form: A table is said to be in 4th normal form when it is in 3rd normal form and has no multi -valued
dependencies.
5th Normal Form: A table is said to be in 5th normal form when it is in 4th normal forma and every join dependency for the
entity is a consequence of its candidate keys.
Distinct Clause allows you to display unique from the result set. This can be used with only select statements.
3. What are the DDL Commands and the Purpose of these commands?
DDL (Data Definition Language) command is used for defining the structure of the Data. DDL Statements are auto
commit.
• CREATE - to create objects in the database
• ALTER - alters the structure of the database
• DROP - delete objects from the database
• TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
• COMMENT - add comments to the data dictionary
• RENAME - rename an object
4. What are the DML commands and Use Of these commands?
DML (Data Manipulation Language) statements are used for managing data within schema objects.
• INSERT - insert data into a table
• UPDATE - updates existing data within a table
• DELETE - deletes all records from a table, the space for the records remain
DML Statements can be roll backed.
DML Statements can’t be roll backed When DDL Statement Executed immediately after the DML statement.
5. What are the DCL Commands and purpose of it?
DCL is Data Control Language statements.
o GRANT - gives user's access privileges to database
o REVOKE - withdraw access privileges given with the GRANT command
(Transaction Control Language) Manages the changes made by DML statements. These commands allow statements to
be grouped together into logical transactions.
o COMMIT - save work done
o SAVEPOINT - identify a point in a transaction to which you can later roll back
o ROLLBACK - restore database to original since the last COMMIT
7. What is the Difference between TRUNCATE and DROP?
Truncate Delete the entire data from the table and keeps the structure.
TRUCATE TABLE table name
DROP drops the table structure also.
DROP TABLE Table name
8. What is the Difference between TRUNCATE and DELETE?
9. What is NULL?
NULL in Oracle is an Absence of information. A NULL can be assigned but not evaluated by it self also.
NULL not equal to null
NULL Can not be Not equal to NULL (Neither Equal Not Not Equal)
NULL Does not equal to empty String or doe not equal to ZERO.
1) EQUI JOIN: The equi join is normally used to join tables with primary key foreign key relation ships.
2) NON-EQUI JOIN:
A join condition where any relation operator other than "=" equal to
operator is used.
3) OUTER JOIN:
In EQUI JOIN rows that does not satisfy specified condition would not be displayed. Example: consider EMO and DEPT
table as Example
DEPTNO 40 is not displayed in the Equi example because there are no employees in it. If we want to diplay its detail also
then we have to use OUTER JOIN.Otherwise OUTER JOIN is imilar to EQUI JOIN except for the difference it uses outer
join (+) operator. (A plus within parenthesis) towards the side not having required data. Outer join operator will substitute
null values when there are no values available.
SQL> SELECT E.DEPTNO,ENAME,DNAME FROM EMP E , DEPT D
2 WHERE E.DEPTNO (+) = D.DEPTNO;
4) SELF JOIN:
When we join a table to itself it is called self join.To join a table itself means that each row of the table is combined with
itself and with every other row of the table. The self join can be seen as join of two copies of the same table.
All columns in SELECT List that are not in group functions must be in the GROUP BY clause.
NO, We Can’t.
17. How can we restrict the Group Results?
SUBQUERY :
A query within another quey. A select statement whose output is substituted in the condition of another select
statement .(A query is a statement written for returning specific data). The subquery is executed only once. A subquery is
enclosed in parenthesis.
EX: SQL> SELECT ENAME FROM EMP
WHERE DEPTNO = (SELECT DEPTNO FROM EMP
WHERE ENAME = 'SMITH');
CORRELATED QUERY:
In a correlated subquery the table used in outer query refers to the table used in the inner query. The correlated
subquery is executed repeatedly once
for each row of the main query table.
Query to display name of highest salary taker.
SQL> SELECT EMPNO, ENAME FROM EMP A
WHERE 1 > ( SELECT COUNT(*) FROM EMP B
WHERE A.SAL < B.SAL)
20. You are updating the table, you ask some another user to logon to database to check your changes before you issue
the commit command ? Can he see the changes done by you?
Another user can’t see the the changes done by you until you have given commit.
Provides the ability to conditionally update or insert data into a database table.
Performs update if the row exists and an insert if it is a new row.
Ex : Insert Statement
24. What are the Difference between UNION and UNION ALL?
25. If you a Table A, You want to create table B having the same fields in TABLE A ? That means you have to copy only
structure not the data?
Level
For each row returned by heirachical query the level pseudo columns returns 1 for root row , 2 for child row of the root
and so on.
It is Best to use CASE Statement when comparing ranges or more complex logic
SQL Statement in the FROM clause of SQL statement called Inline View. Oracle treats the data set that is returned from
the inline view as if it were a table.
This is not a schema Object.
A common use for inline views in oracle sql is to simplify the complex queries by removing join operations and
condensinfg several separate queries into single query.
37. What are Constraints? And what are the constraint Types?
NOTNULL:
UNIQUE:
Not allow already existing value
Is defined either table level or column level
PRIMARY KEY:
Doesn’t allow Nulls and already existing values.
CREATE TABLE T1( X1 NUMBER,
X2 VARCHAR2(10),
CONSTRAINT x2_UK PRIMARY KEY(X2))
FOREIGN KEY:
Foreign Key defines the column in the child table at table constraint level.
CHECK
Defines a condition that each row must satisfy
If view is complex View and View contains the following then we can’t modify the view
--GROUP Functions
-- A Group By clause
-- DISTINCT Keyword
-- Not null columns in Base table that are not selected by View
1) 2 rows selected
2) No rows selected
DELETE FROM EMPMASTER A WHERE A.ROWID> (SELECT MIN(B.ROWID) FROM EMPMASTER B WHERE
A.EMPNO=B.EMPNO);
SELECT DISTINCT (A.SAL) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (B.SAL)) FROM EMP B
WHERE A.SAL<=B.SAL)
56. What is the difference Between Primary Key and Unique Key?
PL/SQL:
Syntax:
TYPE type_name AS TABLE OF element_type
Ex:
CREATE TYPE Stulist AS TABLE OF VARCHAr2(10)
/
CREATE TYPE student AS OBJECT (
id NUMBER,
name VARCHAR2(10),
stuinfo stulist)
Syntax:
TYPE type_name AS VARRAY(size limit) OF element_type
Ex:
CREATE TYPE Stulist AS VARRAY(50) OF VARCHAr2(10)
/
CREATE TYPE student AS OBJECT (
id NUMBER,
name VARCHAR2(10),
stuinfo stulist)
Syntax :
TYPE type_name IS TABLE OF element type
INDEX BY BINARY_INTEGER
Associated Arrays are appropriate for relatively small lookup tables where the collection can be constructed in
memory each time a procedure is called or Package is initialized. These are good for collecting information whose value is
unknown before hand, because there is no fixed limit on their size.
A DML statement can transfer all the elements of a collection in a single operation, a process known as bulk
binding.
For example If the collection has 20 elements, bulk binding lets you perform the equivalent of 20 SELECT, INSERT,
UPDATE, or DELETE statements using a single operation.
This technique improves performance by minimizing the number of context switches between the PL/SQL and
SQL engines
FOR c1 in C2 LOOP
Var1 =c2.ename;
Var2 = c2.empno;
END LOOP;
16. What is the difference between OPEN-FETCH-CLOSE and FOR LOOP in CURSORS?
FOR LOOP in CURSOR:
A cursor FOR loop implicitly declares its loop index as a %ROWTYPE record, opens a cursor, repeatedly fetches
rows of values from the result set into fields in the record, and closes the cursor when all rows have been processed.
OPEN-FETCH-CLOSE:
Ref cursor is a Data type. A variable created using this data type is usually called as 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.)
It is of two types:
* Uses the same memory area for all the active sets created by different queries.
* Can be used to pass result sets between sub programs.
* Ability to change the query based on a certain criterion.
Static Cursors cannot be passed to sub programs whereas ref cursors can be passed between sub programs.
Static Cursors as the name suggests are Static and decided at the design time itself whereas Ref Cursors are changed
during the execution time as per certain criterion.
Important Note: Ensure that any open cursor is closed before attempting to open the next cursor.
declare
type r_cursor is REF CURSOR;
c_emp r_cursor;
er emp%rowtype;
begin
open c_emp for select * from emp;
loop
fetch c_emp into er;
exit when c_emp%notfound;
dbms_output.put_line(er.ename ' - ' er.sal);
end loop;
close c_emp;
end;
Positional Notation :
Acc_update(acct,amt);
Named Notation : acc_update(amount =>amt, acct_no => acct);
Or
Acc_update(acct_no=>acct,amount=>amt);
Mixed Notation:
Positional Notation must precede named notation. And the reverse notation is not allowed.
Acc_update(acct,amount => amt);
35. What are the Parameter Modes and what is the default parameter mode?
Parameter Modes are IN,OUT,INOUT
36. In Parameter modes which are pass by Reference and Pass by Value?
Pass By Reference : IN
Pointer to the actual parameter is passed to the corresponding formal parameters. Both Parameters use
the same memory location.
NOCOPY is Compiler Hint. When the Parameters hold large data structures such as collections and records , all
this time copying slows down the execution. To prevent this we ca specify NOCPY. This allows the PL/SQL Compiler to
pass OUT and INOUT parameters by reference.
39. What is PL/SQL Package? And what are the parts of the package?
Package groups logically related PL/SQL types, procedures, functions.
Package having the two parts: Package specification and Package Body.
• When you call the Packaged Procedure for the first time ,the whole package is loaded in to memory. So
later calls to related subprograms in the package require no disk I/O.
• Packages stop cascading dependencies and thereby avoid unnecessary recompiling.
41. What are Private and Public variables in Package?
• Variables declared in Package Body and restricted to use with in the package those variables are called Private
Variables.
• Variables declared in Package specification and this variable is Visible outside the package ,those variables are
called public variables.
42. Which Package can we use to display the output from the PL/SQL blocks or subprogram?
DBMS_OUTPUT
43. Which statement we have to set to display output on SQL*PLUS?
SET SERVEROUTPUT ON
44. How to read and write the text files?
Using UTL_FILE
50. What is the difference Between Row Level Trigger and Statement Level Trigger?
• Row level trigger executes once for each row after (or before) the event. This is defined By using FOR EACH
ROW
• Statement Level trigger executes once after (or before) the event, independent how many rows are affected by the
event.
Plsql table is one dimentional, unbounded, collection of elements indexed by binary interger.
plsql table can have only one column,it is similar to one dimentional array.
it is onbounded there is no predefined limit of the number od rows in plsql table.
The plsql table is in this way very different from aray.
plsql table can have only single column, all rows in plsql table contain of the values of same data type.
Indexed by binary integer
Plsql tables correctly supports a single index mode by binary integer.
This number acts as primary key od plsql table.
You can’t commit information to plsql table or rollback changes from the table.
You can’t select from plsql table.
You can’t isssue DML statemts.
Materialiazed Views
It is special kind of views which physically exists inside the database,it can contain joins or aggragate functions to improve
performances .
The existances of materiliazed views is transparent to sql applications,so DBA can create or drop materiliazed views of any
time without affecting the sql applications.
Pcakage :
A package is a schema object that groups logically related PL/SQL types, items, and subprograms. Packages usually have
two parts, a specification and a body, although sometimes the body is unnecessary. The specification (spec for short) is the
interface to your applications; it declares the types, variables, constants, exceptions, cursors, and subprograms available for
use. The body fully defines cursors and subprograms, and so implements the spec.
Exceptions :
An exception is a runtime error or warning condition, which can be predefined or user-defined. Predefined exceptions are
raised implicitly (automatically) by the runtime system. User-defined exceptions must be raised explicitly by RAISE
statements. To handle raised exceptions, you write separate routines called exception handlers
ACCESS_INTO_NULL 06530 -6530 A program attempts to assign values to the attributes of an uninitialized
object
CASE_NOT_FOUND 06592 -6592 None of the choices in the WHEN clauses of a CASE statement is selected,
Object Types :
• An object type is a user-defined composite datatype representing a data structure and functions and procedures
to manipulate the data. With scalar datatypes, each variable holds a single value. With collections, all the elements
have the same type. Only object types let you associate code with the data.
• The variables within the data structure are called attributes. The functions and procedures of the object type are
called methods
Advangates with object types :
• Object types let you break down a large system into logical entities. This lets you create software components
that are modular, maintainable, and reusable across projects and teams.
To see how objects can be used, suppose an object is created to represent a person. In this case, a person is defined by three
attributes: first_name, last_name and date_of_birth. Returning the age of the person is also desired, so this is included as a
member function, get_age.
CREATE OR REPLACE TYPE t_person AS OBJECT (
first_name VARCHAR2(30),
last_name VARCHAR2(30),
date_of_birth DATE,
MEMBER FUNCTION get_age RETURN NUMBER
);
/
Type created.
Next the type body is created to implement the get_age member function.
CREATE OR REPLACE TYPE BODY t_person AS
MEMBER FUNCTION get_age RETURN NUMBER AS
BEGIN
RETURN tRUNC(MONTHS_BETWEEN(SYSDATE, date_of_birth)/12);
END get_age;
END;
/
Type body created.
Once the object is defined, it can be used to define a column in a database table.
CREATE TABLE people (
id NUMBER(10) NOT NULL,
person t_person
);
Table created.
To insert data into the PEOPLE table, the t_person() constructor must be used. This can be done as part of a regular DML
statement or using PL/SQL.
INSERT INTO people (id, person)
VALUES (1, t_person('John', 'Doe', TO_DATE('01/01/2000','DD/MM/YYYY')));
1 row created.
COMMIT;
Commit complete.
DECLARE
l_person t_person;
BEGIN
A principal use of methods is to provide access to the data of an object. You can define methods for operations that an
application is likely to want to perform on the data so that the application does not have to code these operations itself. To
perform the operation, an application calls the appropriate method on the appropriate object.
For example, the following SQL statement uses the get_idno() method to display the Id number of persons in the contacts
table:
You can also define static methods to compare object instances and to perform operations that do not use any particular
object's data but instead are global to an object type.A constructor method is implicitly defined for every object type, unless
this default constructor is over-written with a user-defined constructor. A constructor method is called on a type to
construct or create an object instance of the type.
Using an ALTER TYPE statement, you can modify, or evolve, an existing user-defined type to make the following changes:
• _ Add and drop attributes
• _ Add and drop methods
• _ Modify a numeric attribute to increase its length, precision, or scale
• _ Modify a varying length character attribute to increase its length
• _ Change a type's FINAL and INSTANTIABLE properties
Object Tables
• An object table is a special kind of table in which each row represents an object. For
• example, the following statement creates an object table for person_typ objects:
• CREATE TABLE person_obj_table OF person_typ;
• You can view this table in two ways:
• _ As a single-column table in which each row is a person_typ object, allowing
• you to perform object-oriented operations
• _ As a multi-column table in which each attribute of the object type person_typ;
• such as idno, name, and phone; occupies a column, allowing you to perform
• relational operations
You can use a REF to examine or update the object it refers to. You can also use a REF to obtain the object it refers to. You
can change a REF so that it points to a different object of the same object type hierarchy or assign it a null value.
Dereferencing REFs
Accessing the object referred to by a REF is called dereferencing the REF. Oracle provides the DEREF operator to do this.
Dereferencing a dangling REF returns a null object. For example:
SELECT DEREF(c.contact_ref), c.contact_date FROM contacts_ref c;
Oracle also provides implicit dereferencing of REFs. For example, to access the manager's name for an employee, you can
use a SQL expression similar to the following:
SELECT e.name, e.manager.name FROM emp_person_obj_table
WHERE e.name = 'Bob Jones';
In the example, e.manager.name follows the pointer from the person's manager, and retrieves the manager's name.
Following the REF like this is allowed in SQL, but not in PL/SQL.
Obtaining REFs
You can obtain a REF to a row object by selecting the object from its object table and applying the REF operator. For
example, you can obtain a REF to the person with identification number 1 as follows:
Declare
person_ref REF person_typ;
BEGIN
SELECT REF(p) INTO person_ref
FROM person_obj_table p
WHERE p.idno = 1;
END;
• Oracle does not ensure that the object references stored in such columns point to valid and existing row objects.
Therefore, REF columns may contain object references that do not point to any existing row object. Such REF
values are referredto as dangling references.
• A REF column may be constrained to be scoped to a specific object table. All the REF values stored in a column
with a SCOPE constraint point at row objects of the table specified in the SCOPE clause. The REF values may,
however, be dangling.
• PRIMARY KEY constraints cannot be specified for REF columns. However, you can specify NOT NULL
constraints for such columns.
Collections
For modeling multi-valued attributes and many to many relationships, Oracle supports two collection datatypes: varrays
and nested tables. Collection types can be used anywhere other datatypes can be used. You can have object attributes of a
collection type in addition to columns of a collection type. For example, you might give a purchase order object type a
nested table attribute to hold the collection of line items for a given purchase order.
You use the CREATE TYPE statement to define collection types. In Example 1–3, the CREATE TYPE statements define the
object types people_typ and dept_persons_typ.
In this simplified example, people_typ is a collection type, specifically a nested table type. The dept_persons_typ object
type has an attribute people_typ of this type. Each row in the people_typ nested table is an object of type person_typ.
You can define indexes on leaf-level scalar attributes of column objects, as shown in the following example. You can only
define indexes on REF attributes or columns if the REF is scoped.
Here, dept_addr is a column object, and city is a leaf-level scalar attribute of dept_addr that we want to index:
Wherever Oracle expects a column name in an index definition, you can also specify a scalar attribute of an object column.
You can define triggers on an object table just as you can on other tables. You cannot define a trigger on the storage table
for a nested table column or attribute. You cannot modify LOB values in a trigger body. Otherwise, there are no special
restrictions on using object types with triggers.
The following example defines a trigger on the office_tab table defined in "Constraints for Object Tables" on page 2-4.
What is an Index?
An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each value
that appears in the indexed columns. By default, Oracle creates B-tree indexes.
Create an Index
The syntax for creating a index is:
CREATE [UNIQUE] INDEX index_name
ON table_name (column1, column2, . column_n)
[ COMPUTE STATISTICS ];
There are several types of indexes available in Oracle all designed for different circumstances:
• b*tree indexes - the most common type (especially in OLTP environments) and the default type
• b*tree cluster indexes - for clusters
• hash cluster indexes - for hash clusters
• reverse key indexes - useful in Oracle Real Application Cluster (RAC) applications
• bitmap indexes - common in datawarehouse applications
• partitioned indexes - also useful for datawarehouse applications
• function-based indexes
• index organised tables
• domain indexes
Let's look at these Oracle index types in a little more detail.
B*Tree Indexes
B*tree stands for balanced tree. This means that the height of the index is the same for all values thereby ensuring that
retrieving the data for any one value takes approximately the same amount of time as for any other value. Oracle b*tree
indexes are best used when each value has a high cardinality (low number of occurrences)for example primary key indexes
or unique indexes. One important point to note is that NULL values are not indexed. They are the most common type of
index in OLTP systems.
B*Tree Cluster Indexes
These are B*tree index defined for clusters. Clusters are two or more tables with one or more common columns and are
usually accessed together (via a join).
For example consider a car manufacturer which records information about cars sold including the colour of each car. Each
Partition indexes can either be created as local partitioned indexes or global partitioned indexes. Local partitioned indexes
means that the index is partitioned on the same columns and with the same number of partitions as the table. For global
partitioned indexes the partitioning is user defined and is not the same as the underlying table.
Function-based Indexes
As the name suggests these are indexes created on the result of a function modifying a column value. For example
The function must be deterministic (always return the same value for the same inputs).
Index Organised Tables
In an index-organised table all the data is stored in teh Oracle database in a B*tree index structure defined on the table's
primary key. This is ideal when related pieces of data must be stored together or data must be physically stored in a
specific order. Index-organised tables are often used for information retrieval, spatial and OLAP applications.
Domain Indexes
These indexes are created by user-defined indexing routines and enable the user to define his or her own indexes on
custom data types (domains) such as pictures, maps or fingerprints for example. These type of index require in-depth
knowledge about the data and how it will be accessed.
Bulk Collect :
‘Bulk collect..into’ clause improve performance of the select statements. To loop through records collected using bulk
collect we can use FORALL syntax. FORALL clause works with DML statements in batches and much faster than the
regular for loop construct. In this blog post, we are going to talk about FORALL exceptions with the
%BULK_EXCEPTIONS attribute. This attribute allows us to continue with the process, even if run into any DML exception
for some record in between. Basically this mechanism allows us to complete the process without stopping if any error
occurs.
All exceptions raised during execution are saved in %BULK_EXCEPTION attribute. It also stores a collection of records
similar to BULK COLLECT. It has two fields.
• %BULK_EXCEPTIONS(i).ERROR_CODE holds the corresponding Oracle error code.
• %BULK_EXCEPTIONS(i).ERROR_INDEX holds the iteration number of the FORALL statement for which the
exception was raised.
• %BULK_EXCEPTIONS.COUNT holds total number of exceptions encountered.
In order to bulk collect exceptions, we have to use FORALL clause with SAVE EXCEPTIONS keyword. Let us see with the
example.
Connect to SQL*Plus with proper credentials and run following query to create the table and populate it with some data.
CREATE TABLE TEST
(
Test_ID NUMBER(9) NOT NULL PRIMARY KEY,
Test_Desc VARCHAR(30),
New_Desc VARCHAR(30)
)
/
SQL> INSERT INTO TEST(TEST_ID,TEST_DESC)
2 SELECT ROWNUM, TABLE_NAME
3 FROM USER_TABLES;
i := utl_file.fgetpos(InFile);
dbms_output.put_line(TO_CHAR(i));
2. Is it possible to have DML operations (Insert , Update , Delete ) STATEMENTS in a database trigger .?
Is it possible to have DML operations ( Insert , Update , Delete ) STATEMENTS in a database trigger .
Yes, you can do but not on the table on which the trigger is created. Otherwise, you can run into Mutating table
or tansition table state error.
Pragma is a keyword in Oracle PL/SQL that is used to provide an instruction to the compiler.
1.PRAGMA EXCEPTION_INIT(message,SQLCODE);---------->Exceptions
Pragma exception_init Allow you to handle the Oracle predefined message by your own message. Means you
can instruct compiler to associate the specific message to oracle predefined message at compile time. This way
you improve the Readability of your program, and handle it according to your own way.
Example : sqlerrr error code 1400 is can’t insert null value this message we can instruct to compiler our own
message.
DECLARE
e_MissingNull EXCEPTION;
PRAGMA EXCEPTION_INIT (e_MissingNull, -1402);
BEGIN
INSERT INTO Employee (id) VALUES (NULL);
EXCEPTION
WHEN e_MissingNull then
DBMS_OUTPUT.put_line('ORA-1400 occurred');
END;
Output:
pkg.n: 10
sr_pkg.n: 5
7. What is Raise_application_error?
It is a procedure of package DBMS_STANDARD which allows to issue an user_defined error messages from stored
sub program or database trigger. we can define a user defined error message with error number in case of an
exception.
syntax: RAISE_APPLICATION_ERROR(errnum,'errmsg');
Example :
create or replace procedure new_emp
( p_name in emp.ename%type
, p_sal in emp.sal%type
, p_job in emp.job%type
, p_dept in emp.deptno%type
, p_mgr in emp.mgr%type
, p_hired in emp.hiredate%type := sysdate )
is
invalid_manager exception;
PRAGMA EXCEPTION_INIT(invalid_manager, -2291);
dummy varchar2(1);
begin
-- check hiredate is valid
if trunc(p_hired) > trunc(sysdate)
then
raise_application_error
(-20000
, 'NEW_EMP::hiredate cannot be in the future');
end if;
end;
/
Materialized View s:
Syntax :
CREATE MATERIALIZED VIEW [schema.]mview
Mview_Options
[USING INDEX storage_options]
[{REFRESH [refresh_options] | NEVER REFRESH]
[FOR UPDATE] [{ENABLE|DISABLE} QUERY REWRITE]
AS subbquery;
Mview_Options:
storage_options:
PCTFREE int
PCTUSED int
INITRANS int
MAXTRANS int
STORAGE storage_clause
TABLESPACE tablespace
refresh_options:
FAST | COMPLETE | FORCE
ON [DEMAND | COMMIT]
{NEXT | START WITH} date
WITH {PRIMARY KEY | ROWID}
USING DEFAULT {MASTER|LOCAL} ROLLBACK SEGMENT
USING {MASTER|LOCAL} ROLLBACK SEGMENT rb_segment
idx_organized_tbl_clause:
storage_option(s)
{MAPPING TABLE | NOMAPPING}
[PCTTHRESHOLD int]
[COMPRESS int|NOCOMPRESS]
[ [INCLUDING column_name] OVERFLOW [storage_option(s)] ]
external_table_clause:
([TYPE access_driver_type]
DEFAULT DIRECTORY directory [ACCESS PARAMETERS {USING CLOB subquery |
(opaque_format_spec) }]
LOCATION (directory:'location_specifier'
[,directory2:'location_specifier2'...)
) [REJECT LIMIT {int|UNLIMITED}]
nested_storage_clause:
NESTED TABLE {nested_item | COLUMN_VALUE}
• Can be updated even when disconnected from the master site or master materialized view site.
• Requires fewer resources than multimaster replication.
• Are refreshed on demand. Hence the load on the network might be reduced compared to using
multimaster replication because multimaster replication synchronises changes at regular intervalls.
1. sys.snap$ and sys.mlog$ are updated to reflect the time of the refresh.
2. The materialized base view is truncated.
1. sys.snap$ and sys.mlog$ are updated to reflect the time of the refresh.
2. Rows in the materialized base view are deleted.
3. All rows selected from the master table are inserted into the snapshot base table.
4. sys.slog$ is updated to reflect the time of the refresh.
5. Rows that are not needed anymore for a refresh by any materialized view are deleted from the
materialized view log (<schema name>.MLOG$_table)
If a materialized view is being refreshed can be checked by querying the type of v$lock: if the type is JI a
refresh is being performed.
The following query checks for this:
select
o.owner "Owner",
o.object_name "Mat View",
username "Username",
s.sid "Sid"
from
v$lock l,
dba_objects o,
v$session s
where
o.object_id = l.id1 and
l.type ='JI' and
l.lmode = 6 and
s.sid = l.sid and
o.object_type = 'TABLE'
SQL Tuning
1. Find the problem to a single SQL
You may be lucky and know already the exact SQL causing the problem. If so, move straight on to the second step. Otherwise, click on
the link above for help on finding the problem SQL.
2. Analyze the SQL to determine the nature of the problem
Most performance problems are quite common and easy to fix. This section will describe some of these and how to spot them, and then
go on to describe a more general analysis method.
3. Fix the problem.
Almost every performance problem has a solution; it’s just that some are more complex than others. In order of increasing complexity
and expense, such fixes include:
• Analyze the underlying table to give Oracle’s Cost Based Optimizer the information it needs to resolve the SQL
efficiently.
• Add one or more hints to the SQL to encourage or discourage certain execution plans.
• Minor changes to the SQL to encourage or discourage certain execution plans.
• All keywords (SQL Verbs) should be in Upper Case. (e.g. – SELECT, FROM, WHERE etc.)
• Put less cardinality fields on left side in the where clause of the SQL statements.
SELECT info
FROM taba a, tabb b, tabc c
WHERE a.acol between :alow and :ahigh
AND b.bcol between :blow and :bhigh
AND c.ccol between :clow and :chigh
AND a.key1 = b.key1
AMD a.key2 = c.key2;
Thus, if the range of :alow to :ahigh is narrow compared with the range of acol, but the ranges of :b* and :c*
are relatively large, then table taba should be the driving table, all else being equal.
• Use Care When Using IN and NOT IN with a Subquery, Remember that WHERE (NOT) EXISTS is a useful alternative.
• Indexes improve the performance of queries that select a small percentage of rows from a table. As a general guideline,
create indexes on tables that are queried for less than 2% or 4% of the table’s rows. This value may be higher in
situations where all data can be retrieved from an index, or where the indexed columns and expressions can be used
for joining to other tables.
Oracle's V$ Views
To be finished...
The following views are part of the data dictionary.
See also Oracle's x$ tables
v$archive_dest
Shows all archived redo log destinations. Use this view to find out to which place archived redo logs are
copied: select dest_id,destination from v$archive_dest
These values correspond to the init parameter log_archive_dest_n.
v$archive_dest_status
This view allows to find status and errors for each of the defined
v$archived_log
Displays successfully archived redo logs.
shows received logs on a primary standby database.
v$archive_gap
Lists sequence numbers of the archived los that are known to be missing for each thread on a (physical?)
standby database (highest gap only).
v$archive_processes
This view provides information on the archive processes. It can be used to find out if an ARCH process is
active or not.
v$controlfile
Displays the location and status of each controlfile in the database.
v$controlfile_record_section
See sections in a controlfile.
v$bh
This dynamic view has an entry for each block in the database buffer cache.
The column status can be:
• free
This block is not in use
v$buffer_pool
See buffer pools.
This view's column id can be joined with x$kcbwds.indx
See also x$kcbwbpd
v$buffer_pool_statistics
v$database
This view lets you access database information. For example, you can check (using log_mode) whether or
not the database is in archivelog mode:
ADPDB>select log_mode from v$database;
LOG_MODE
------------
ARCHIVELOG
checkpoint_change# records the SCN of the last checkpoint.
switchover_status: can be used to determine if it is possible to perform a switchover operation Only
available for physical standby databases. Can be:
• NOT ALLOWED,
• SESSIONS ACTIVE,
• SWITCHOVER PENDING,
• SWITCHOVER LATENT,
• TO PRIMARY,
• TO STANDBY or
• RECOVERY NEEDED.
See protection modes in data guard for the columns protection_mode and protection_level.
database_role determines if a database is a primary or a logical standby database or a physical standby
database.
force_logging tells if a database is in force logging mode or not.
v$datafile
This view contains an entry for each datafile of the database.
This view can be used to find out which datafiles must be backed up in a cold backup: select name from
v$datafile
COUNT(*)
----------
185
If you want to know, which x$ tables there are, do a select name from v$fixed_table where name
like 'X$%';
v$fixed_view_definition
Contains the defintion in its attribute view_definition for the views of v$fixed_table.
v$flash_recovery_area_usage
See also v$recovery_file_dest
v$instance
instance_role can be used to determine if an instance is an active instance (=primary instance) or a
secondary instance (in a standby environment.
dbms_utility.db_version can be used to retrieve the same version as the field version in v$instance.
v$instance_recovery
Can, for example, be used to determine the optimal size of redo logs.
v$latch
Oracle collects statistics for the activity of all latches and stores these in this view. Gets is the number of
successful willing to wait requests for a latch. Similarly, misses is how many times a process didn't
successfully request a latch. Spin_gets: number of times a latch is obtained after spinning at least once.
Sleeps indicates how many times a willing to wait process slept. Waiters_woken tells how often a sleeping
process was 'disturbed'.
• 1: null,
• 2: Row Share (SS),
• 3: Row Exclusive (SX),
• 4: Share (S),
• 5: Share Row Exclusive (SSX) and
• 6: Exclusive(X)
If the lock type is TM, the column id1 is the object's id and the name of the object can then be queried like
so: select name from sys.obj$ where obj# = id1
A lock type of JI indicates that a materialized view is being refreshed.
A more detailed example can be found here
See also x$kgllk.
v$locked_object
Who is locking what:
select
oracle_username
os_user_name,
locked_mode,
object_name,
object_type
from
v$locked_object a,dba_objects b
where
a.object_id = b.object_id
v$log
Contains information on each log group. See also online redo log.
Comman values for the status column are:
• UNUSED:
Oracle8 has never written to this group,
• CURRENT:
This is the active group.
• ACTIVE:
Oracle has written to this log before, it is needed for instance recovery.
The active log is the one with the current log sequence number
• INACTIVE:
Oracle has written to this log before; it is not needed for instance recovery.
v$object_usage
v$object_usage gathers information about used (accessed) indexes when an index is monitored using alter
index ... monitoring usage.
See On verifying if an index is used.
v$open_cursor
v$option
This view lets you see which options are installed in the server.
See also dba_registry.
v$parameter
Lists the name-value pairs of the init.ora file (or their default, if not in the init.ora). For example, if you
need to know what your block size is:
select value from v$parameter where name = 'db_block_size'
-- desc of target
target_desc varchar2(32) := 'A long running procedure';
dbms_application_info.set_module('long_proc',null);
dbms_application_info.set_session_longops (
rindex,
slno);
if mod(sofar,1000) = 0 then
dbms_application_info.set_session_longops (
rindex,
slno,
op_name,
target,
context,
sofar,
totalwork,
target_desc,
units);
end if;
end loop;
declare
v_stmt varchar2(16000);
v_sql_text v$sqltext_with_newlines.sql_text%type;
v_sid v$session.sid%type;
begin
for r in (
select
sql_text,s.sid
from
v$sqltext_with_newlines t,
v$session s
where
s.sql_address=t.address
order by s.sid, piece) loop
v_sid := nvl(v_sid,r.sid);
end loop;
dbms_output.put_line(v_sid);
dbms_output.put_line(v_stmt,100);
end;
/
Thanks to Sarmad Zafar who notified me of an error in this PL/SQL Block.
Note: the function put_line is found here and can be used to prevent ORU-10028.
• dba_tables
• dba_tab_columns
• dba_all_tables
• dba_tab_comments
• dba_col_comments
• dba_external_tables
• dba_external_locations
• dba_tab_histograms
• dba_tab_statistics
• dba_tab_col_statistics
• dba_tab_modifications
• dba_encrypted_columns
• dba_registry,
• dba_registry_hierarchy,
• dba_registry_history,
• dba_registry_log
• dba_xml_schemas
• dba_xml_tables
• dba_xml_views
• dba_xml_views_cols
• dba_audit_exists
• dba_audit_object
• dba_audit_policies
• dba_audit_policy_columns
• dba_audit_session
• dba_audit_statement
• dba_audit_trail
• dba_common_audit_trail
• dba_fga_audit_trail
• dba_opj_audit_opts
• dba_priv_audit_opts
• dba_repaudit_attribute
• dba_repaudit_column
• dba_stmt_audit_option_opts
• plsql_ccflags
• plsql_code_type
• plsql_debug
• plsql_optimize_level
• plsql_warnings
• nls_length_semantics
dba_procedures
The column procedure_name is null for procedures and functions, it is only set for procedures and
functions in pl/sql packages. The procedures' and functions' names are found in the column object_name,
however, using dba_procedures, it is not possible to find out if it is a procedure or function. This is possible
with dba_objects.
dba_profiles
Allows to see the profiles and their settings.
dba_queues
dba_queue_tables
See drop table.
dba_recyclebin
Displays the object in the recycle bin for the currently logged on user.
recyclebin is a synonym for user_recyclebin.
dba_refresh
dba_registered_mview_groups
This is a view that belongs to the replication catalog.
See also materialized view group.
dba_registry
dba_repcat_refresh_templates
This is a view that belongs to the replication catalog.
dba_repcat_template_objects
This is a view that belongs to the replication catalog.
Prepared By Venu Thamatam
Venu.thamatam@gmail.com Page 53
It keeps track of deployent templates.
dba_repcat_template_parms
This is a view that belongs to the replication catalog.
dba_repcat_template_sites
This is a view that belongs to the replication catalog.
dba_repcat_user_authorizations
This is a view that belongs to the replication catalog.
dba_repcat_user_parm_values
This is a view that belongs to the replication catalog.
dba_repcatlog
This is a view that belongs to the replication catalog.
It can be used to track administrative requests.
dba_repcolumn
This is a view that belongs to the replication catalog.
dba_repcolumn_group
This is a view that belongs to the replication catalog.
dba_repconflict
This is a view that belongs to the replication catalog.
dba_repddl
This is a view that belongs to the replication catalog.
dba_repextensions
This is a view that belongs to the replication catalog.
dba_repgenobjects
This is a view that belongs to the replication catalog.
dba_repgroup
This is a view that belongs to the replication catalog.
dba_repgroup_privileges
This is a view that belongs to the replication catalog.
dba_repgrouped_column
This is a view that belongs to the replication catalog.
dba_repkey_columns
This is a view that belongs to the replication catalog.
dba_repobject
This is a view that belongs to the replication catalog.
dba_repparameter_column
This is a view that belongs to the replication catalog.
dba_reppriority
This is a view that belongs to the replication catalog.
dba_reppriority_group
This is a view that belongs to the replication catalog.
dba_repprop
This is a view that belongs to the replication catalog.
dba_represol_stats_control
This is a view that belongs to the replication catalog.
dba_represolution
This is a view that belongs to the replication catalog.
dba_represolution_method
This is a view that belongs to the replication catalog.