Вы находитесь на странице: 1из 37

Oracle Application Developers Guide.

Points
System Development life cycle (SDLC) Normalization PL/SQL Data Types Brief descriptions of the predefined exceptions in PL/SQL Cursor Attributes. Loops in PL/SQL Parameter types UTL_FILE Current of cursor Locking Dynamic SQL Materialized view Pragma Reference Cursor Implicit and Explicit Cursor Bulk Collection Dead Lock Mutating Table DBMS_PIPE Table Joins Trigger Types

System Development Life Cycle


PHASE AND PURPOSE
Phase 1: PLANNING

Required to determine the feasibility of whether the project should proceed or not. Produces a high level overview document of the project which relates to the project requirements and scope. To include requirements for data replication to the warehouse.

Phase 2: DEFINITION

Defines what, when, who, and how the project will be carried out. This phase expands on the high-level project outline and provides a specific and detailed project definition. This phase assumes that an RFP has been prepared and distributed, a contract project development team chosen and a Project Manager appointed.

Phase 3: ANALYSIS

Required to understand and document the user's needs for the system.

Documents in detail the scope, business objectives and requirements of the system. Emphasizes what the system is to do . Includes analysis of what data needs to be replicated to the data warehouse.

Phase 4: DESIGN

Describes how the proposed system is to be built. The design is specific to the technical requirements the system will be required to operate in and the tools used in building the system. Impacts the build and implementation phases of the SDLC. Describes movement of data between operational databases and the data warehouse.

Phase 5: BUILD

Deals with the development, unit testing and integration testing of the system modules, screens and reports and data replication to the data warehouse if required. Carried out in parallel with the development of user procedures and user documentation from the implementation phase. Prepare for and carry out the implementation of the developed system through user acceptance testing to full production and warehouse population.

Phase 6: IMPLEMENTATION

Explain normalization with examples.


1NF A relation R is in first normal form (1NF) if and only if all underlying domains contain atomic values only

Example: 1NF but not 2NF


FIRST (supplier_no, status, city, part_no, quantity)

Functional Dependencies:
(supplier_no, part_no) quantity (supplier_no) status (supplier_no) city city status (Supplier's status is determined by location)

Comments:
Non-key attributes are not mutually independent (city status). Non-key attributes are not fully functionally dependent on the primary key (i.e., status and city are dependent on just part of the key, namely supplier_no).

Anomalies:
INSERT: We cannot enter the fact that a given supplier is located in a given city until that supplier supplies at least one part (otherwise, we would have to enter a null value for a column participating in the primary key C a violation of the definition of a relation). DELETE: If we delete the last (only) row for a given supplier, we lose the information that the supplier is located in a particular city. UPDATE: The city value appears many times for the same supplier. This can lead to inconsistency or the need to change many values of city if a supplier moves.

Decomposition (into 2NF):


SECOND (supplier_no, status, city) SUPPLIER_PART (supplier_no, part_no, quantity)
2NF A relation R is in second normal form (2NF) if and only if it is in 1NF and every non-key attribute is fully dependent on the primary key

Example (2NF but not 3NF):


SECOND (supplier_no, status, city)

Functional Dependencies:
supplier_no status supplier_no city city status

Comments:
Lacks mutual independence among non-key attributes. Mutual dependence is reflected in the transitive dependencies: supplier_no city, city status.

Anomalies:
INSERT: We cannot record that a particular city has a particular status until we have a supplier in that city. DELETE: If we delete a supplier which happens to be the last row for a given city value, we lose the fact that the city has the given status. UPDATE: The status for a given city occurs many times, therefore leading to multiple updates and possible loss of consistency.

Decomposition (into 3NF):


SUPPLIER_CITY (supplier_no, city) CITY_STATUS (city, status)

3NF A relation R is in third normal form (3NF) if and only if it is in 2NF and every non-key attribute is non-transitively dependent on the primary key. An attribute C is transitively dependent on attribute A if there exists an attribute B such that: A-> B and B->C. Note that 3NF is concerned with transitive dependencies which do not involve candidate keys. A 3NF relation with more than one candidate key will clearly have transitive dependencies of the form: primary_key -> other_candidate_key -> any_non-key_column

An alternative (and equivalent) definition for relations with just one candidate key is:
A relation R having just one candidate key is in third normal form (3NF) if and only if the nonkey attributes of R (if any) are: 1) mutually independent, and 2) fully dependent on the primary key of R. A non-key attribute is any column which is not part of the primary key. Two or more attributes are mutually independent if none of the attributes is functionally dependent on any of the others. Attribute Y is fully functionally dependent on attribute X if X Y, but Y is not functionally dependent on any proper subset of the (possibly composite) attribute X

For relations with just one candidate key, this is equivalent to the simpler:
A relation R having just one candidate key is in third normal form (3NF) if and only if no nonkey column (or group of columns) determines another non-key column (or group of columns)

Example (3NF but not BCNF):


SUPPLIER_PART (supplier_no, supplier_name, part_no, quantity)

Functional Dependencies:
We assume that supplier_name's are always unique to each supplier. Thus we have two candidate keys: (supplier_no, part_no) and (supplier_name, part_no) Thus we have the following dependencies: (supplier_no, part_no) quantity (supplier_no, part_no) supplier_name (supplier_name, part_no) quantity (supplier_name, part_no) supplier_no supplier_name supplier_no supplier_no supplier_name

Comments:
Although supplier_name supplier_no (and vice versa), supplier_no is not a non-key column it is part of the primary key! Hence this relation technically satisfies the definition(s) of 3NF (and likewise 2NF, again because supplier_no is not a non-key column).

Anomalies:
INSERT: We cannot record the name of a supplier until that supplier supplies at least one part. DELETE: If a supplier temporarily stops supplying and we delete the last row for that supplier, we lose the supplier's name. UPDATE: If a supplier changes name, that change will have to be made to multiple rows (wasting resources and risking loss of consistency).

Decomposition (into BCNF):


SUPPLIER_ID (supplier_no, supplier_name) SUPPLIER_PARTS (supplier_no, part_no, quantity)
BCNF A relation R is in Boyce-Codd normal form (BCNF) if and only if every determinant is a candidate key
The definition of BCNF addresses certain (rather unlikely) situations which 3NF does not handle. The characteristics of a relation which distinguish 3NF from BCNF are given below. Since it is so unlikely that a relation would have these characteristics, in practical real-life design it is usually the case that relations in 3NF are also in BCNF. Thus many authors make a "fuzzy" distinction between 3NF and BCNF when it comes to giving advice on "how far" to normalize a design. Since relations in 3NF but not in BCNF are slightly unusual, it is a bit more difficult to come up with meaningful examples. To be precise, the definition of 3NF does not deal with a relation that:

has multiple candidate keys, where those candidate keys are composite, and the candidate keys overlap (i.e., have at least one common attribute) Example:
An example of a relation in 3NF but not in BCNF (and exhibiting the three properties listed) was given above in the discussion of 3NF. The following relation is in BCNF (and also in 3NF): SUPPLIERS (supplier_no, supplier_name, city, zip) We assume that each supplier has a unique supplier_name, so that supplier_no and supplier_name are both candidate keys.

Functional Dependencies:
supplier_no -> city supplier_no -> zip supplier_no -> supplier_name supplier_name -> city supplier_name -> zip supplier_name -> supplier_no

Comments:
The relation is in BCNF since both determinants (supplier_no and supplier_name) are unique (i.e., are candidate keys). The relation is also in 3NF since even though the non-primary-key column supplier_name determines the non-key columns city and zip, supplier_name is a candidate key. Transitive dependencies involving a second (or third, fourth, etc.) candidate key in addition to the primary key do not violate 3NF. Note that even relations in BCNF can have anomalies. Anomalies: INSERT: We cannot record the city for a supplier_no without also knowing the supplier_name DELETE: If we delete the row for a given supplier_name, we lose the information that the supplier_no is associated with a given city. UPDATE: Since supplier_name is a candidate key (unique), there are none. Decomposition: SUPPLIER_INFO (supplier_no, city, zip) SUPPLIER_NAME (supplier_no, supplier_name) Larry Newcomer (Updated)

PL/SQL DATA TYPES


PL/SQL data types can be broken down into the following categories: 1. Scalar 1.1. Character/String 1.2. Number 1.3. Boolean 1.4. Date/Time 2. Reference 2.1. REF_CURSOR 2.2. REF 3. Composite 3.1. Records 3.2. Nested Tables 3.3. Index-by tables 3.4. varrays 4. LOB

Brief descriptions of the predefined exceptions in PL/SQL

Exception

ACCESS_INTO_NULL

ORA-06530

Sql Error code -6530

Raise When Your program attempts to assign values to the attributes of an uninitialized (atomically null) object. Your program attempts to apply collection methods other than EXISTS to an uninitialized (atomically null) nested table or varray, or the program attempts to assign values to the elements of an uninitialized nested table or varray. Your program attempts to open an already open cursor. A cursor must be closed before it can be reopened. A cursor FOR loop automatically opens the cursor to which it refers. So, your program cannot open that cursor inside the loop. Your program attempts to store duplicate values in a database column that is constrained by a unique index. Your program attempts an illegal cursor operation such as closing an unopened cursor. In a SQL statement, the conversion of a character string into a number fails because the string does not represent a valid number. (In procedural statements, VALUE_ERROR is raised.) Your program attempts to log on to Oracle with an invalid username and/or password.

COLLECTION_IS_NULL

ORA-06531

-6531

CURSOR_ALREADY_OPEN

ORA-06511

-6511

DUP_VAL_ON_INDEX

ORA-00001

-1

INVALID_CURSOR INVALID_NUMBER

ORA-01001 ORA-01722

-1001 -1722

LOGIN_DENIED

ORA-01017

-1017

NO_DATA_FOUND

ORA-01403

+100

NOT_LOGGED_ON PROGRAM_ERROR ROWTYPE_MISMATCH

ORA-01012 ORA-06501 ORA-06504

-1012 -6501 -6504

SELF_IS_NULL

ORA-30625

30625

STORAGE_ERROR SUBSCRIPT_BEYOND_COU NT

ORA-06500 ORA-06533

-6500 -6533

SUBSCRIPT_OUTSIDE_LIMI T

ORA-06532

-6532

SYS_INVALID_ROWID

ORA-01410

-1410

A SELECT INTO statement returns no rows, or your program references a deleted element in a nested table or an uninitialized element in an index-by table. SQL aggregate functions such as AVG and SUM always return a value or a null. So, a SELECT INTO statement that calls a aggregate function will never raise NO_DATA_FOUND. The FETCH statement is expected to return no rows eventually, so when that happens, no exception is raised. Your program issues a database call without being connected to Oracle. PL/SQL has an internal problem. The host cursor variable and PL/SQL cursor variable involved in an assignment have incompatible return types. For example, when an open host cursor variable is passed to a stored subprogram, the return types of the actual and formal parameters must be compatible. Your program attempts to call a MEMBER method on a null instance. That is, the built-in parameter SELF (which is always the first parameter passed to a MEMBER method) is null. PL/SQL runs out of memory or memory has been corrupted. Your program references a nested table or varray element using an index number larger than the number of elements in the collection. Your program references a nested table or varray element using an index number (-1 for example) that is outside the legal range. The conversion of a character

TIMEOUT_ON_RESOURCE TOO_MANY_ROWS VALUE_ERROR

ORA-00051 ORA-01422 ORA-06502

-51 -1422 -6502

string into a universal rowid fails because the character string does not represent a valid rowid. A time-out occurs while Oracle is waiting for a resource. A SELECT INTO statement returns more than one row. An arithmetic, conversion, truncation, or size-constraint error occurs. For example, when your program selects a column value into a character variable, if the value is longer than the declared length of the variable, PL/SQL aborts the assignment and raises VALUE_ERROR. In procedural statements, VALUE_ERROR is raised if the conversion of a character string into a number fails. (In SQL statements, INVALID_NUMBER is raised.) Your program attempts to divide a number by zero.

ZERO_DIVIDE

ORA-01476

-1476

Give Name of Different Cursor Attributes.


Attribute Name %FOUND Description The % FOUND attribute test whether a FETCH returned a record. The return value is of Boolean type. If TRUE, a row was returned by the FETCH. If FALSE, a row was not returned. %NOTFOUND is the opposite of %FOUND. It returns TRUE if a row was not returned by the FETCH and FALSE if one was returned. This tests for the number of rows fetched from the cursor at any given time and returns a number. This attribute tests to see if a cursor is already open. If TRUE, the cursor is open. If FALSE, it is not open Also used for Bulk collect operations, this attribute provides information regarding the number of rows changed during the operation. This attributes is used for array of Bulk collect operations. It provides information regarding exceptions encountered during such operations.

%NOTFOUND %ROWCOUNT %ISOPEN %BULK_ROWCOUNT %BULK_EXCEPTIONS

Loops in PL/SQL

Simple Loops The most basic kind of loop, they include LOOP, END LOOP, and some method to exit. e.g. LOOP action; END LOOP; Numeric FOR Loops With this loop structure we can define the number of times the loop will cycle beore exiting. FOR counter in low_number..high_number LOOP Action; END LOOP; While Loops This type of loop executes only while a certain condition is met.when it no longer meets the condition, this loop ends. WHILE condition LOOP Action; END LOOP;

Parameter Mode
Mode IN Description The value of the actual parameter is passed into the procedure when the procedure is invoked. Inside the procedure, the formal parameter acts like a PL/SQL constant it is considered read-only and cannot be changed. When the procedure finishes and control returns to the calling environment, the actual parameter is not changed. Any value the actual parameter has when the procedure is called is ignored. Inside the procedure, the formal parameter acts like an uninitialized PL/SQL variable and thus has a value of NULL. It can be read from and written to. When the procedure finishes and control returns to the calling environment, the contents of the formal parameter are assigned to the actual parameter. This mode is a combination of IN and OUT. The value of the actual parameter is passed into the procedure when the procedure is invoked. Inside the procedure, the formal parameter acts like initialized variable and can be read from and written to. When the procedure finishes and control returns to the calling environment, the contents of the formal parameter are assigned to the actual parameter

OUT

IN OUT

Passing Parameters by Reference and by value A Subprogram parameter can be passed in one of two ways by reference or by value. When a parameter is passed by reference, a pointer to the actual parameter is passed to the corresponding formal parameter. When a parameter is passed by value on the other hand, it is copied from the actual parameter into the formal parameter. Passing by reference is generally faster, because it avoids the copy. By default PL/SQL will pass IN parameters by reference, and IN OUT and OUT parameter by value. If NOCOPY is present, the PL/SQL compiler will try to pass the parameter by reference, rather than by value. Using NOCOPY on an IN parameter will generate a compilation error, because IN parameters are always passed by reference and thus NOCOPY doesnt apply.

The primary advantage of NOCOPY is that it may increase performance. This is especially valuable when passing the large PL/SQL arrays. Parameter Passing Methods For a procedure that contains multiple parameters, you can use a number of methods to specify the values of the parameters. Method Description Positional Lists values in the order in which the parameters are declared Named association Lists values in arbitrary order by associating each one with its parameter name, using special syntax (=>) Combination Lists the first values positionally, and the remainder using the special syntax of the named method.

The UTL_FILE package : Procedures and Functions


Function or Procedures FOPEN IS_OPEN GET_LINE Description A function the opens a file for input or output and returns a file handle used in subsequent I/O operations. A Function that returns a Boolean value whenever a file handle refers to an open file A procedure that reads a line of text from the opened file and places the text in the output buffer parameter (the maximum size of an input records is 1023 bytes unless you specify a larger size in the overloaded version of FOPEN) A Procedure that writes a text string stored in the buffer parameter to the opened file (no line terminator is appended by put; use new_line to terminate the line, or use PUT_LINE to write a complete line with a terminator) A formatted put procedure with two format specifires : %s and \n (use %s to substitute a value into the output string. \n Is a new line character Procedure that terminates a line in an output file Procedure that writes all data buffered in memory to a file Procedure that closes an opened file Procedure that closes all opened file handles for the session

PUT, PUT_LINE

PUTF NEW_LINE FFLUSH FCLOSE FCLOSE_ALL

Exceptions to the UTL_FILE Packages Exception Name INVALID_PATH INVALID_MODE INVALID_FILEHANDLE INVALID_OPERATION READ_ERROR WRITE_ERROR INTERNAL_ERROR Description The file location or filename was invalid The OPEN_MODE parameter in FOPEN was invalid The file handle was invalid The file could not be opened or operated on as requested An operating system error occurred during the read operation An Operating system error occurred during the write operation An unspecified error occurred in PL/SQL

SELECT FOR UPDATE in Cursors


When you issue a SELECT statement against the database to query some records, no locks are placed on the selected rows. In general, this is a wonderful feature because the number of records

locked at any given time is (by default) kept to the absolute minimum: only those records which have been changed but not yet committed are locked. Even then, others will be able to read those records as they appeared before the change (the "before image" of the data). There are times, however, when you will want to lock a set of records even before you change them in your program. Oracle offers the FOR UPDATE clause of the SELECT statement to perform this locking. When you issue a SELECT...FOR UPDATE statement, the RDBMS automatically obtains exclusive row-level locks on all the rows identified by the SELECT statement, holding the records "for your changes only" as you move through the rows retrieved by the cursor. No one else will be able to change any of these records until you perform a ROLLBACK or a COMMIT. Here are two examples of the FOR UPDATE clause used in a cursor: CURSOR toys_cur IS SELECT name, manufacturer, preference_level, sell_at_yardsale_flag FROM my_sons_collection WHERE hours_used = 0 FOR UPDATE;

CURSOR fall_jobs_cur IS SELECT task, expected_hours, tools_required, do_it_yourself_flag FROM winterize WHERE year = TO_CHAR (SYSDATE, 'YYYY') FOR UPDATE OF task; The first cursor uses the unqualified FOR UPDATE clause, while the second cursor qualifies the FOR UPDATE with a column name from the query. You can use the FOR UPDATE clause in a SELECT against multiple tables. In this case, rows in a table are locked only if the FOR UPDATE clause references a column in that table. In the following example the FOR UPDATE clause does not result in any locked rows in the winterize table:

CURSOR fall_jobs_cur IS SELECT w.task, w.expected_hours, w.tools_required, w.do_it_yourself_flag FROM winterize w, husband_config hc WHERE year = TO_CHAR (SYSDATE, 'YYYY') FOR UPDATE OF husband_config.max_procrastination_allowed;

The FOR UPDATE OF clause only mentions the max_procrastination_allowed column; no columns in the winterize table are listed.

The OF list of the FOR UPDATE clause does not restrict you to changing only those columns listed. Locks are still placed on all rows; the OF list just gives you a way to document more clearly what you intend to change. If you simply state FOR UPDATE in the query and do not include one or more columns after the OF keyword, then the database will then lock all identified rows across all tables listed in the FROM clause. Furthermore, you do not have to actually UPDATE or DELETE any records just because you issued a SELECT...FOR UPDATE -- that act simply states your intention to be able to do so. Finally, you can append the optional keyword NOWAIT to the FOR UPDATE clause to tell Oracle not to wait if the table has been locked by another user. In this case, control will be returned immediately to your program so that you can perform other work or simply wait for a period of time before trying again. Without the NOWAIT clause, your process will block until the table is available. There is no limit to the wait time unless the table is remote. For remote objects, the Oracle initialization parameter, DISTRIBUTED_LOCK_TIMEOUT, is used to set the limit. Releasing Locks with COMMIT As soon as a cursor with a FOR UPDATE clause is OPENed, all rows identified in the result set of the cursor are locked and remain locked until your session issues either a COMMIT statement to save any changes or a ROLLBACK statement to cancel those changes. When either of these actions occurs, the locks on the rows are released. As a result, you cannot execute another FETCH against a FOR UPDATE cursor after you COMMIT or ROLLBACK. You will have lost your position in the cursor. Consider the following program, which assigns winterization chores:[1] [1] Caveat: I don't want to set false expectations with anyone, especially my wife. The code in this block is purely an example. In reality, I set the max_procrastination_allowed to five years and let my house decay until I can afford to pay someone to do something, or my wife does it, or she gives me an ultimatum. Now you know why I decided to write a book... DECLARE /* All the jobs in the Fall to prepare for the Winter */ CURSOR fall_jobs_cur IS SELECT task, expected_hours, tools_required, do_it_yourself_flag FROM winterize WHERE year = TO_CHAR (SYSDATE, 'YYYY') AND completed_flag = 'NOTYET' FOR UPDATE OF task; BEGIN /* For each job fetched by the cursor... */

FOR job_rec IN fall_jobs_cur LOOP IF job_rec.do_it_yourself_flag = 'YOUCANDOIT' THEN /* || I have found my next job. Assign it to myself (like someone || is going to do it!) and then commit the changes. */ UPDATE winterize SET responsible = 'STEVEN' WHERE task = job_rec.task AND year = TO_CHAR (SYSDATE, 'YYYY'); COMMIT; END IF; END LOOP; END;

Suppose this loop finds its first YOUCANDOIT job. It then commits an assignment of a job to STEVEN. When it tries to FETCH the next record, the program raises the following exception:

ORA-01002: fetch out of sequence If you ever need to execute a COMMIT or ROLLBACK as you FETCH records from a SELECT FOR UPDATE cursor, you should include code (such as a loop EXIT or other conditional logic) to halt any further fetches from the cursor. 6.11.2 The WHERE CURRENT OF Clause PL/SQL provides the WHERE CURRENT OF clause for both UPDATE and DELETE statements inside a cursor in order to allow you to easily make changes to the most recently fetched row of data. The general format for the WHERE CURRENT OF clause is as follows:

UPDATE table_name SET set_clause WHERE CURRENT OF cursor_name;

DELETE FROM table_name WHERE CURRENT OF cursor_name;

Notice that the WHERE CURRENT OF clause references the cursor and not the record into which the next fetched row is deposited.

The most important advantage to using WHERE CURRENT OF where you need to change the row fetched last is that you do not have to code in two (or more) places the criteria used to uniquely identify a row in a table. Without WHERE CURRENT OF, you would need to repeat the WHERE clause of your cursor in the WHERE clause of the associated UPDATEs and DELETEs. As a result, if the table structure changes in a way that affects the construction of the primary key, you have to make sure that each SQL statement is upgraded to support this change. If you use WHERE CURRENT OF, on the other hand, you only have to modify the WHERE clause of the SELECT statement.

This might seem like a relatively minor issue, but it is one of many areas in your code where you can leverage subtle features in PL/SQL to minimize code redundancies. Utilization of WHERE CURRENT OF, %TYPE, and %ROWTYPE declaration attributes, cursor FOR loops, local modularization, and other PL/SQL language constructs can have a big impact on reducing the pain you may experience when you maintain your Oracle-based applications.

Let's see how this clause would improve the previous example. In the jobs cursor FOR loop above, I want to UPDATE the record that was currently FETCHed by the cursor. I do this in the UPDATE statement by repeating the same WHERE used in the cursor because (task, year) makes up the primary key of this table:

WHERE task = job_rec.task AND year = TO_CHAR (SYSDATE, 'YYYY'); This is a less than ideal situation, as explained above: I have coded the same logic in two places, and this code must be kept synchronized. It would be so much more convenient and natural to be able to code the equivalent of the following statements: Delete the record I just fetched. or: Update these columns in that row I just fetched. A perfect fit for WHERE CURRENT OF! The next version of my winterization program below uses this clause. I have also switched to a simple loop from FOR loop because I want to exit conditionally from the loop:

DECLARE CURSOR fall_jobs_cur IS SELECT ... same as before ... ; job_rec fall_jobs_cur%ROWTYPE; BEGIN OPEN fall_jobs_cur; LOOP FETCH fall_jobs_cur INTO job_rec;

IF fall_jobs_cur%NOTFOUND THEN EXIT;

ELSIF job_rec.do_it_yourself_flag = 'YOUCANDOIT' THEN UPDATE winterize SET responsible = 'STEVEN' WHERE CURRENT OF fall_jobs_cur; COMMIT; EXIT; END IF; END LOOP; CLOSE fall_jobs_cur; END;

What is the difference between Implicit Cursor & Explicit Cursor? Explicit Cursors The Cursor is declared, using a SELECT statement, in the declaration section of any block. The developer controls almost all operations involving the cursor. Implicit Cursors Implicit cursors are controlled by PL/SQL, and are created whenever any DML or SELECT .. INTO statement is run. Give Name of Implicit Cursor Attributes.

SQL%ROWCOUNT SQL%NOTFOUND SQL%FOUND What is difference between Static SQL and Dynamic SQL? PL/SQL supports both static and dynamic SQL. The syntax of static SQL statements is known at precompile time and the preparation of the static SQL occurs before runtime, where as the syntax of dynamic SQL statements is not known until runtime. Dynamic SQL is a programming technique that makes your applications more flexible and versatile. Your programs can build and process SQL data definition, data control, and session control statements at run time, without knowing details such as table names and WHERE clauses in advance. What is difference between %TYPE and %ROWTYPE If the variable we are declaring maps directly to a column in the database, we can anchor our variable type to the database type given to that column with %TYPE. %ROWTYPE is similar to %TYPE in that it anchors a variable to the table it is tied to. %ROWTYPE anchors the variable to all columns in the table, thought, not just one. How can I protect/hide my PL/SQL source code? Using wrapper utility you can hide the code. The wrapper utility does not encrypt the code. Instead, it converts it to hexadecimal digits so that it cannot be read or edited. To run the utility, use the following syntax. Wrap iname=input_file.sql oname=output_file.plb Give Syntax of IF-THEN-ELSIF IF condition THEN Action ELSIF condition THEN Action ELSE Action ENDIF; Give Syntax of CASE CASE expression WHEN test1 THEN action; WHEN test2 THEN action; . END CASE; What is circular Expression? Circular expression refers to the ability to repeatedly execute code until some condition is met. PL/SQL uses loops to accomplish this.

What is Autonomous Transactions? Autonomous transaction are started by a parent, or main, transaction but operate independently of the parent for transaction control. If a commit or rollback is used in the autonomous or main transaction, or if a failure occurs for any reason, it does not impact the other transaction. To create an autonomous transaction, use a pragma called AUTONOMUS TRANSACTION. e.g. CREATE OR REPLACE PROCEDURE logging_ins( I_username IN VARCHAR2, I_datetime IN TIMESTAMP) IS PRAGMA AUTONOMOUS_TRANSACTION; BEGIN INSERT INTO LOGGIN (USERNAME, DATETIME) VALUES ( I_USERNAME,I_DATETIME); COMMIT; END; / What is Dynamic SQL? Dynamic SQL is built and run during the execution of the block. It does this using either the built-in package called DBMS_SQL or Native Dynamic SQL (NDS) The built-in package DBMS_SQL provides a few dozen procedures and functions that enable the use of dynamic SQL including DDL. NDS uses a single command, EXECUTE IMMEDIATE, to run statements dynamically within the PL/SQL block. What is inline view? Inline view are subselects in the FROM clause that act as a view at execution time. They are not named view, stored in the database. What is a Record? A record provides the means of defining a programming structure. A programming structure is a set of variable types. They are grouped together and managed as a unit. Record types map to a stored definition of the structure. A record type is a programming structure that mirrors a single row in a table. Since there is only row in any record , a record contains fields rather than column. What is a Collection? Types? Collection are lists, which may be ordered or unordered. Ordered lists are indexed by unique subscripts; unordered lists are indexed by unique identifiers, which may be numbers, hash values or string names. Associate arrays (index-by tables) Nested tables Varrays

TYPE type_name IS {VARRAY | VARYING ARRAY} (size limit) OF element_type [NOT NULL]; e.g.

DECLARE TYPE integer_varray is ARRAY(3) of INTEGER; Varray_integer integer_varray := integer_varray (NULL,NULL,NULL); Give some examples of Analytical functions. RANK ROLLUP CUBE GROUPING Give Name of Character Functions in Oracle ASCII DECOMPOSE INSTRB LENGTHB NCHR REGEXP_INST R TRIM SUBSTRB UPPER ASCIISTR INITCAP INSTRC LENGTHC NLS_INITCAP REGEXP_REP LACE SOUNDEX SUBSTRC CHR INSTR LENGTH LOWER NLS_LOWER REGEXP_SUB STR SUBSTR TRANSLATE COMPOSE INSTR2 LENGTH2 LPAD LS_UPPER REPLACE SUBSTR2 TRIM CONCAT INSTR4 LENGTH4 LTRIM NLSSORT RPAD SUBSTR4 UNISTR

Give Name of Numeric Functions in Oracle ABS COS POWER TAN LN CEIL MOD SQRT ATAN2 SIGN LOG SINH ATAN FLOOR TRUNC SIN ASIN EXP ROUNDTANH ACOS COSH REMAINDER BITAND

Give Name of Date Functions in Oracle ADD_MONTHS MONTHS_BET SYSTIMESTA WEEN MP TO_DSINTERV CURRENT_TI NEXT_Day AL ME NUMTODSINT TO_TIMESTA EXTRACT ERVAL MP FROM_TZ SESSIONTIME TO_YMINTER ZONE VAL TRUNC LOCALTIMEST SYSDATE AMP Give Name of Conversion Functions in Oracle CASE RAWTONHEX TO_CHAR ROWIDTOCHA R TO_DATE RAWTOHEX TO_CLOB TO_SINGLE_B YTE TO_BINARY_F TO_NUMBER HEXTORAW TO_NCHAR

CURRENT_DA TE TO_TIME ROUND LAST_DAY TZ_OFFSET

NEW_TIME CURRENT_TI MESTAMP TO_TIMESTAM P_TZ SYS_EXTRAC T_UTC

TO_NCLOB CONVERT TO_BLOB

CHARTOROWI D TO_BINARY_D OUBLE TO_MULTI_BY TE

LOAT Give Name of Other Functions in Oracle BFILENAME EMPTY_CLOB NLS_CHARSE T_NAME GREATEST NULLIF UID NVL USER DEREF USERENV DUMP NLS_CHARSE T_DECL_LEN EMPTY_BLOB NLS_CHARSE SYS_GUID T_ID TREAT DECODE NANVL SYS_CONTEX T VSIZE COALESCE LEAST REF VALUE

HOW TO CREATE A DATABASE LINK?

A database link is an object in the local database that allows you to access objects on a remote database or to mount a secondary database in read-only mode. CREATE [PUBLIC] DATABASE LINK dblink [CONNECT TO user IDENTIFIED BY password] [USING connect_string]

1) 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 are the different types of joins? 1. Equijoins 2. Non-Equijoins 3. Outer Joins Left Outer Joins Right Outer Joins Full Outer Joins 4. Self Join 5. Cross Join What cursor type do you use to retrieve multiple recordsets?

REF cursor in oracle


How will you copy the structure of a table without copying the data?

create table xyz as ( select * from abc where 1=0) What is Pseudo column? A pseudo column is an item of data which does not belong in any particular table but which can be treated as if it did. Any SELECT list of columns can include these pseudo columns. SYSDATE CURRVAL NEXTVAL LEVEL ROWID ROWNUM UID USER

PRAGMA EXCEPTION_INIT Tells the 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. Declare PRAGMA EXCEPTION_INIT(e_emps_Remaining,-2292); BEGIN .. EXCEPTION WHEN e_emps_remaining THEN END;

What is overloading? You can create multiple subprograms with the same name in the same package, each taking parameters of different number or datatype. PL/SQL Tables and records in packages Create or replace package emp_package is TYPE emp_table_type is table of employees%ROWTYPE Index by binary_integer; Procedure read_Emp_table (p_emp_table out emp_table_type); End emp_package; Most of the standard packages are created by running catproc.sql What are advantages of packages ? Modularity : Encapsulate related constructs Easier application design: code and compile specification and body separately Hiding information :

Only the declarations in the package Specification are visible and accessible to applications Private constructs in the package body are hidden and inaccessible All coding is hidden in the package body. Group logically related PL/SQL types , items and subprograms Allow the oracle server to read multiple objects into memory at once. A package specification can exist without a package body ? Yes, but a package body can not exist without a package specification. Write syntax for creating the package? CREATE [OR REPLACE] PACKAGE package_name IS | AS Public type and item declarations Subprogram specifications END package name; What is a LOB? LOBs are used to store large unstructured data such as text, graphic images, films, and sound waveforms. There are four large object data types: BLOB represents a binary large object, such as a video clip. CLOB represents a character large object. NCLOB represents a multibyte character large object. BFILE represents a binary file stored in an operating system binary file outside the database. THE BFILE column or attribute stores a file locator that points to the external file. LOBs are characterized in two ways, according to their interpretation by the oracle server (binary or character) and their storage aspects. LOBs can be stored internally (inside the database) or in host files. There are two categories of LOBs: 1. Internal LOBs (CLOB, NCLOB, BLOB) are stored in the database. 2. External files (BFILE) are stored outside the database. e.g Large Text CLOB Photo BLOB Movie BFILE What are Bfiles? BFILEs are external large objects (LOBs) stored in operating system files outside of the database tablespaces. The oracle SQL data type to support these large objects is BFILE data type stores a locator to the physical file. NOTE : Oracle Backup and recovery methods support only the LOB locators, not the physical BFILEs. What is a trigger? Trigger defines an action the database should take when some database related event occurs. Difference - Primary Key and Aggregate Key

Primary Key is a much similar to unique key. Only difference is that unique key can be null but primary key can not be null. Primary key is used to avoid duplication of data. A primary key consists of more than one column. Also known as a concatenated key or Aggregate Key. it is also called as composite key. What are different types of Triggers? A trigger is a PL/SQL block or a PL/SQL procedure associated with table, view, schema, or the database. Executes implicitly whenever a particular event takes place Can be either : 1. Application trigger : Fires whenever an event occurs with a particular application 2. Database trigger : Fires whenever a data event (Such as DML) or system event (such as logon or shutdown) occurs on a schema or database Statement Trigger A Statement trigger is fired once on behalf of the triggering event, even if no rows are affected at all. Statement triggers are useful if the trigger action does not depend on the data from rows that are affected or on data provided by the triggering event itself: for example a trigger that performs a complex security check on the current user. Row Trigger A row trigger fires each time the table is affected by the triggering event. If the triggering event affects no rows, a row trigger is not executed. Row triggers are useful if the trigger action depends on data of rows that are affected or on data provided by the triggering event itself. NOTE : The size of the trigger cannot be more than 32K Trigger Firing Sequence Before Statement trigger Before Row Trigger After Row Trigger After Statement Trigger How can one see if somebody modified any code? Code for stored procedures, functions and packages is stored in the Oracle Data Dictionary. One can detect code changes by looking at the LAST_DDL_TIME column in the USER_OBJECTS dictionary view. Example: SELECT OBJECT_NAME, TO_CHAR(CREATED, 'DD-Mon-RR HH24:MI') CREATE_TIME, TO_CHAR(LAST_DDL_TIME, 'DD-Mon-RR HH24:MI') MOD_TIME, STATUS FROM USER_OBJECTS WHERE LAST_DDL_TIME > '&CHECK_FROM_DATE';

How can one search PL/SQL code for a string/ key value? The following query is handy if you want to know where a certain table, field or expression is referenced in your PL/SQL source code. SELECT TYPE, NAME, LINE FROM USER_SOURCE WHERE UPPER(TEXT) LIKE '%&KEYWORD%'; How can one keep a history of PL/SQL code changes? One can build a history of PL/SQL code changes by setting up an AFTER CREATE schema (or database) level trigger (available from Oracle 8.1.7). This way one can easily revert to previous code should someone make any catastrophic changes. Look at this example: CREATE TABLE SOURCE_HIST -- Create history table AS SELECT SYSDATE CHANGE_DATE, USER_SOURCE.* FROM USER_SOURCE WHERE 1=2; CREATE OR REPLACE TRIGGER change_hist -- Store code in hist table AFTER CREATE ON SCOTT.SCHEMA -- Change SCOTT to your schema name DECLARE BEGIN if DICTIONARY_OBJ_TYPE in ('PROCEDURE', 'FUNCTION', 'PACKAGE', 'PACKAGE BODY', 'TYPE') then -- Store old code in SOURCE_HIST table INSERT INTO SOURCE_HIST SELECT sysdate, user_source.* FROM USER_SOURCE WHERE TYPE = DICTIONARY_OBJ_TYPE AND NAME = DICTIONARY_OBJ_NAME; end if; EXCEPTION WHEN OTHERS THEN raise_application_error(-20000, SQLERRM); END; / show errors

Can one print to the screen from PL/SQL? One can use the DBMS_OUTPUT package to write information to an output buffer. This buffer can be displayed on the screen from SQL*Plus if you issue the SET SERVEROUTPUT ON; command. For example set serveroutput on begin dbms_output.put_line('Look Ma, I can print from PL/SQL!!!'); end; /

DBMS_OUTPUT is useful for debugging PL/SQL programs. However, if you print too much, the output buffer will overflow. In that case, set the buffer size to a larger value, eg.: set serveroutput on size 200000 If you forget to set serveroutput on type SET SERVEROUTPUT ON once you remember, and then EXEC NULL;. If you haven't cleared the DBMS_OUTPUT buffer with the disable or enable procedure, SQL*Plus will display the entire contents of the buffer when it executes this dummy PL/SQL block. Note that DBMS_OUTPUT doesn't print blank or NULL lines. To overcome this problem, SET SERVEROUTPUT ON FORMAT WRAP; Look at this example with this option first disabled and then enabled: SQL> SET SERVEROUTPUT ON SQL> begin 2 dbms_output.put_line('The next line is blank'); 3 dbms_output.put_line(''); 4 dbms_output.put_line('The above line should be blank'); 5 end; 6 / The next line is blank The above line should be blank SQL> SET SERVEROUTPUT ON FORMAT WRAP SQL> begin 2 dbms_output.put_line('The next line is blank'); 3 dbms_output.put_line(''); 4 dbms_output.put_line('The above line should be blank'); 5 end; 6 / Can one read/write files from PL/SQL? Included in Oracle 7.3 is an UTL_FILE package that can read and write operating system files. The directory you intend writing to has to be in your INIT.ORA file (see UTL_FILE_DIR=... parameter). Before Oracle 7.3 the only means of writing a file was to use DBMS_OUTPUT with the SQL*Plus SPOOL command. Copy this example to get started: DECLARE fileHandler UTL_FILE.FILE_TYPE; BEGIN fileHandler := UTL_FILE.FOPEN('/tmp', 'myfile', 'w'); UTL_FILE.PUTF(fileHandler, 'Look ma, I''m writing to a file!!!\n'); UTL_FILE.FCLOSE(fileHandler); EXCEPTION WHEN utl_file.invalid_path THEN raise_application_error(-20000, 'ERROR: Invalid path for file or path not in INIT.ORA.'); END; / Can one call DDL statements from PL/SQL?

One can call DDL statements like CREATE, DROP, TRUNCATE, etc. from PL/SQL by using the "EXECUTE IMMEDATE" statement. Users running Oracle versions below 8i can look at the DBMS_SQL package (see FAQ about Dynamic SQL). begin EXECUTE IMMEDIATE 'CREATE TABLE X(A DATE)'; end; NOTE: The DDL statement in quotes should not be terminated with a semicolon. Can one use dynamic SQL statements from PL/SQL? Starting from Oracle8i one can use the "EXECUTE IMMEDIATE" statement to execute dynamic SQL and PL/SQL statements (statements created at run-time). Look at these examples. Note that statements are NOT terminated by semicolons: EXECUTE IMMEDIATE 'CREATE TABLE x (a NUMBER)'; -- Using bind variables... sql_stmt := 'INSERT INTO dept VALUES (:1, :2, :3)'; EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, location; -- Returning a cursor... sql_stmt := 'SELECT * FROM emp WHERE empno = :id'; EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id; One can also use the older DBMS_SQL package (V2.1 and above) to execute dynamic statements. Look at these examples: CREATE OR REPLACE PROCEDURE DYNSQL AS cur integer; rc integer; BEGIN cur := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.PARSE(cur, 'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE); rc := DBMS_SQL.EXECUTE(cur); DBMS_SQL.CLOSE_CURSOR(cur); END; / More complex DBMS_SQL example using bind variables: CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO%TYPE) AS v_cursor integer; v_dname char(20); v_rows integer; BEGIN v_cursor := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.PARSE(v_cursor, 'select dname from dept where deptno > :x', DBMS_SQL.V7); DBMS_SQL.BIND_VARIABLE(v_cursor, ':x', no); DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20); v_rows := DBMS_SQL.EXECUTE(v_cursor); loop if DBMS_SQL.FETCH_ROWS(v_cursor) = 0 then

exit; end if; DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname); DBMS_OUTPUT.PUT_LINE('Deptartment name: '||v_dname); end loop; DBMS_SQL.CLOSE_CURSOR(v_cursor); EXCEPTION when others then DBMS_SQL.CLOSE_CURSOR(v_cursor); raise_application_error(-20000, 'Unknown Exception Raised: '||sqlcode||' '||sqlerrm); END; / What is the difference between %TYPE and %ROWTYPE? The %TYPE and %ROWTYPE constructs provide data independence, reduces maintenance costs, and allows programs to adapt as the database changes to meet new business needs. %ROWTYPE is used to declare a record with the same types as found in the specified database table, view or cursor. Example: DECLARE v_EmpRecord emp%ROWTYPE; %TYPE is used to declare a field with the same type as that of a specified table's column. Example: DECLARE v_EmpNo emp.empno%TYPE; What is the result of comparing NULL with NULL? NULL is neither equal to NULL, nor it is not equal to NULL. Any comparison to NULL is evaluated to NULL. Look at this code example to convince yourself. declare a number := NULL; b number := NULL; begin if a=b then dbms_output.put_line('True, NULL = NULL'); elsif a<>b then dbms_output.put_line('False, NULL <> NULL'); else dbms_output.put_line('Undefined NULL is neither = nor <> to NULL'); end if; end; How does one get the value of a sequence into a PL/SQL variable? As you might know, one cannot use sequences directly from PL/SQL. Oracle (for some silly reason) prohibits this: i := sq_sequence.NEXTVAL; However, one can use embedded SQL statements to obtain sequence values:

select sq_sequence.NEXTVAL into :i from dual; Can one execute an operating system command from PL/SQL? There is no direct way to execute operating system commands from PL/SQL in Oracle7. However, one can write an external program (using one of the precompiler languages, OCI or Perl with Oracle access modules) to act as a listener on a database pipe (SYS.DBMS_PIPE). Your PL/SQL program then put requests to run commands in the pipe, the listener picks it up and run the requests. Results are passed back on a different database pipe. For an Pro*C example, see chapter 8 of the Oracle Application Developers Guide. In Oracle8 one can call external 3GL code in a dynamically linked library (DLL or shared object). One just write a library in C/ C++ to do whatever is required. Defining this C/C++ function to PL/SQL makes it executable. Look at this External Procedure example. How does one loop through tables in PL/SQL? Look at the following nested loop code example. DECLARE CURSOR dept_cur IS SELECT deptno FROM dept ORDER BY deptno; -- Employee cursor all employees for a dept number CURSOR emp_cur (v_dept_no DEPT.DEPTNO%TYPE) IS SELECT ename FROM emp WHERE deptno = v_dept_no; BEGIN FOR dept_rec IN dept_cur LOOP dbms_output.put_line('Employees in Department '||TO_CHAR(dept_rec.deptno)); FOR emp_rec in emp_cur(dept_rec.deptno) LOOP dbms_output.put_line('...Employee is '||emp_rec.ename); END LOOP; END LOOP; END; / How often should one COMMIT in a PL/SQL loop? / What is the best commit strategy? Contrary to popular believe, one should COMMIT less frequently within a PL/SQL loop to prevent ORA-1555 (Snapshot too old) errors. The higher the frequency of commit, the sooner the extents in the rollback segments will be cleared for new transactions, causing ORA-1555 errors. To fix this problem one can easily rewrite code like this: FOR records IN my_cursor LOOP ...do some stuff... COMMIT; END LOOP; COMMIT; .. to ...

FOR records IN my_cursor LOOP ...do some stuff... i := i+1; IF mod(i, 10000) = 0 THEN COMMIT; END IF; END LOOP; COMMIT;

-- Commit every 10000 records

If you still get ORA-1555 errors, contact your DBA to increase the rollback segments. NOTE: Although fetching across COMMITs work with Oracle, is not supported by the ANSI standard I can SELECT from SQL*Plus but not from PL/SQL. What is wrong? PL/SQL respect object privileges given directly to the user, but does not observe privileges given through roles. The consequence is that a SQL statement can work in SQL*Plus, but will give an error in PL/SQL. Choose one of the following solutions: Grant direct access on the tables to your user. Do not use roles!

GRANT select ON scott.emp TO my_user; Define your procedures with invoker rights (Oracle 8i and higher); Move all the tables to one user/schema.

What is a mutating and constraining table? "Mutating" means "changing". A mutating table is a table that is currently being modified by an update, delete, or insert statement. When a trigger tries to reference a table that is in state of flux (being changed), it is considered "mutating" and raises an error since Oracle should not return data that has not yet reached its final state. Another way this error can occur is if the trigger has statements to change the primary, foreign or unique key columns of the table off which it fires. If you must have triggers on tables that have referential constraints, the workaround is to enforce the referential integrity through triggers as well. There are several restrictions in Oracle regarding triggers: * A row-level trigger cannot query or modify a mutating table. (Of course, NEW and OLD still can be accessed by the trigger) . * A statement-level trigger cannot query or modify a mutating table if the trigger is fired as the result of a CASCADE delete. Etc. Can one pass an object/table as an argument to a remote procedure? The only way to reference an object type between databases is via a database link. Note that it is not enough to just use "similar" type definitions. Look at this example:

-- Database A: receives a PL/SQL table from database B CREATE OR REPLACE PROCEDURE pcalled(TabX DBMS_SQL.VARCHAR2S) IS BEGIN -- do something with TabX from database B null; END; / -- Database B: sends a PL/SQL table to database A CREATE OR REPLACE PROCEDURE pcalling IS TabX DBMS_SQL.VARCHAR2S@DBLINK2; BEGIN pcalled@DBLINK2(TabX); END; / Is it better to put code in triggers or procedures? What is the difference? In earlier releases of Oracle it was better to put as much code as possible in procedures rather than triggers. At that stage procedures executed faster than triggers as triggers had to be re-compiled every time before executed (unless cached). In more recent releases both triggers and procedures are compiled when created (stored p-code) and one can add as much code as one likes in either procedures or triggers. Is there a PL/SQL Engine in SQL*Plus? No. Unlike Oracle Forms, SQL*Plus does not have an embedded PL/SQL engine. Thus, all your PL/SQL code is sent directly to the database engine for execution. This makes it much more efficient as SQL statements are not stripped off and sent to the database individually. Is there a limit on the size of a PL/SQL block? Yes, the max size is not an explicit byte limit, but related to the parse tree that is created when you compile the code. You can run the following select statement to query the size of an existing package or procedure: SQL> select * from dba_object_size where name = 'procedure_name';

Question 1: What is difference between privileges with grant option and privileges with admin option.? Any global privileges like roles and system privileges (e.g. CREATE TABLE) are granted using the WITH ADMIN OPTION. For table-specific privileges (e.g. GRANT select on emp) we use WITH GRANT OPTION syntax. Also, revoking any grant WITH GRANT will cascade and revoke any and all privileges assigned by the privileged user. On the other hand, revoking someone with the WITH ADMIN OPTION will only revoke their personal privileges, leaving intact all granted users. Question 2: What is Dynamic SQL?

Dynamic SQL is an enhanced form of Structured Query Language (SQL) that, unlike standard (or static) SQL, facilitates the automatic generation and execution of program statements. This can be helpful when it is necessary to write code that can adjust to varying databases, conditions, or servers. It also makes it easier to automate tasks that are repeated many times. Question 3: What is pipe function? The Oracle DBMS_PIPE package provies a mechanism that can be used for indirect communication between two or more co-operating Oracle sessions. Question 4: What is the mutating trigger? What should be the condition? The Oracle mutating trigger error occurs when a trigger references the table that owns the trigger. The best way to avoid this error is use autonomous transaction in triggers so that the child transaction will be independent of the parent transaction. Question 5: How to know the last executed procedure? Select timestamps, owner, obj_name, action_name from dba_audit_trail;this statement gives last executed time for procedure , function & package. Question 6: State the difference between implict and explict cursor's Implicit Cursor are declared and used by the oracle internally. whereas the explicit cursors are declared and used by the user. more over implicitly cursors are no need to declare oracle creates and process and closes autometically. the explicit cursor should be declared and closed by the user. Implicit cursors are used for single row query whereas explicit cursor is used for multiple row query Question 7: What is difference b/w stored procedures and application procedures,stored function and application function.. Stored procedures are subprogrammes stored in the database and can be called &executee multiple times wherein an application procedure is the one being used for a particular application same is the way for function Question 8: Explian rowid,rownum?what are the psoducolumns we have? Rowid is the physical address of the record/row, its in hexadecimal format. rownum is the number given to a row which is fetched by a select statement. Examples for Psudo columns are ROWNUM,SYSDATE,ROWID,LEVEL etc Question 9: What is PL/SQL table ? Objects of type TABLE are called "PL/SQL tables", which are modeled as (but not the same as) database tables , PL/SQL tables use a primary PL/SQL tables can have one column

and a primary key. Question 10: What is Raise_application_error ? Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue an user_defined error messages from stored sub-program or database trigger. Question 11: How many types of database triggers can be specified on a table ? What are they ? DML, Instead-of and System Trigger Question 12: What are correlation identifiers? A correlation identifier is a special kind of PL/SQL bind variables. The colon in front of each indicates that they are bind variables. Question 13: What privilege required to create system trigger? To create system triggers you must have the ADMINISTER DATABASE TRIGGER system privilege. Question 14: What are the different system privileges that apply to triggers? Sr. System Privilege Description 1 CREATE TRIGGER Allows the grantee to create a trigger in his or her own schema. 2 CREEATE ANY Allow the grantee to create triggers in any TRIGGER schema except SYS. It is not recommended to create triggers on data dictionary tables. 3 ALTER ANY TRIGGER Allows the grantee to enable, disable , or compile database trigger in any schema except SYS. Note that if the grantee does not have CREATE ANY TRIGGER, he or she cannot change trigger code. 4 DROP ANY TRIGGER Allows the grantee to drop database triggers in any schema except SYS 5 ADMINISTER Allows the grantee to create or alter a system DATABASE TRIGGER trigger on the database . The grantee must also have either CREATE TRIGGER or CREATE ANY TRIGGER. Question 15: What is mutating table? A mutating table is a table that is currently being modified by a DML statement. Question 16: What are the data types available in PL/SQL ? PL/SQL data types can be broken down into the following categories: 1. Scalar a. Character/String

i. ii. iii. iv. v. vi. vii. viii. ix. x.

Char Long Long Raw Nchar Nvarchar2 RAW ROWID UROWID VARCHAR2 VARCHAR

b. Number i. BINARY_DOUBLE ii. BINARY_FLOAT iii. BINARY_INTEGER iv. NUMBER v. PLS_INTEGER c. Boolean i. True ii. False iii. Null d. Date/Time i. Date ii. Timestamp iii. Timestamp with time zone iv. Timestamp with local time zone v. Interval 2. Reference a. REF_CURSOR b. REF 3. Composite a. Records b. Nested Tables c. Index-by tables d. Varrays 4. LOB Question 17: What is materialized views? A materialized view stores both the definitions of a view and the rows resulting from the execution of the view. Question 18: Can you index and partition the materialized views? Yes

Question 19: What are the different types to refresh materialized views? Fast Force Complete Question 20: Which view is used to find execution plan of a query? V$sql_plan Question 21: What are the various options to move table to different tablespace? Using export and import Using CREATE TABLE .. AS SELECT command Using the ALTER TABLE .. move command Question 22: Differentiate between b-tree index and Bitmap indexes. Sr. B-Tree 1 Suitable for high cardinality columns 2 Updates on keys relatively inexpensive 3 Inefficient for queries using AND/OR predicates 4 Raw-level locking 5 More storage space 6 Useful for OLTP Bitmap Suitable for low-cardinality columns Updates on keys columns very expensive Efficient for queries using AND/OR predicates Bitmap segment level locking Less Storage space Useful for DSS

Question 22: When to create reverse key index? An ever-increasing key i.e. sequential number of invoice. Question 23: Disadvantage of reverse key index? When application statement specify ranges then the reverse key index cannot be used. Question 24: What is clusters? A cluster is a group of one or more tables that share the same data blocks because they share common columns and are often used together in join queries. Question 25: What are different type of clusters? Hash and index Question 26: What are different types of partitioning?

Range, Hash, List and Composite Question 27: What is row-migration? An UPDATE statement increases the amount of data in a row so that the row no longer fits in its data block. The oracle server tries to find another block with the enough free space to hold the entire row. If such a block is available, the oracle server moves the entire row to the new block. The oracle server keeps the original row piece of a migrated row to point to the new block containing the actual row; the rowed of a migrated row does not change. Indexes are not updated; they continue to point to the original row location. Question 28: What is row-chaining? The row is too large to fit into an empty data block. The oracle server stores the data for the row in a chain of two or more data blocks. Chaining can occur when the row is inserted or updated. Row chaining usually occurs with large rows, such as rows that contain a large object (LOB). Row chaining in these cases is unavoidable, unless a larger block size is used. Question 29: Dynamic performance views used for shared-server V$circuit V$dispatcher V$dispatcher_rate V$queue V$shared_server_monitor V$session V$shared_server Question 30: What are the cursor attributes used in PL/SQL ? Oracle provides six attributes that are used with cursors. Sr. Attribute Name 1 %BULK_EXCEPTIONS 2 3 %BULK_ROWCOUNT %FOUND Description This attribute is used for array or Bulk collect operations. It provides information regarding exceptions encountered during such operations. Also used for Bulk Collect operations, this attribute provides information regarding the number of rows changed during the operation. The %FOUND attribute tests whether a FETCH returned a record. The return value is of Boolean type. If TRUE a row was returned by the fetch if FALSE , a row was not returned. This attributes tests to see if a cursor is already open. If TRUE the cursor is open. If false it is not open. %NOTFOUND is the opposite of %FOUND. It returns TRUE if a row was not returned by the FETCH and FLASE if one was reurned. This tests for the number of rows fetched from

4 5 6

%ISOPEN %NOTFOUND %ROWCOUNT

the cursor at any given time and returns a number. Question 31: What is the starting "oracle error number"? ORA-0001 Question 32: What are the return values of functions SQLCODE and SQLERRM ? SQLCODE returns the current error code SQLERRM returns the current error message text Question 33: What is a record? A record provides the means of defining a programming structure. A programming structure is a set of variable types. They are grouped together and managed as a unit. Record types map to a stored definition of a structure. A record type is a programming structure that mirrors a single row in a table. Since there is only a single row in any record, a record contains field rather than columns. Question 34: What are three ways to define record in PL/SQL? 1. Uses the %ROWTYPE attribute 2. Uses explicit definition in the definition section of a PL/SQL program 3. Record type may be defined as a database structure or object type. Question 35: What are Integrity Constraints? Data integrity allows to define certain data quality requirements that the data in the database needs to meet. If a user tries to insert data that doesn't meet these requirements, Oracle will not allow so. There are five integrity constraints in Oracle. Not Null : A column in a table can be specified not null. It's not possible to insert a null in such a column. The default is null. Unique Key The unique constraint doesn't allow duplicate values in a column. If the unique constraint encompasses two or more columns, no two equal combinations are allowed. Primary Key On a technical level, a primary key combines a unique and a not null constraint. Additionally, a table can have at most one primary key. After creating a primary key, it can be referenced by a foreign key. Foreign Key A foreign key constraint (also called referential integrity constraint) on a column ensures that the value in that column is found in the primary key of another table.

Check A check constraint allows to state a minimum requirement for the value in a column. If more complicated requirements are desired, an insert trigger must be used. Question 36: What is alert log file? What information logged in it? Why should it check regularly? Alert log file consists of a chronological log of messages and errors. It is important for the database administrator to check the alert log file regularly to detect problems before they become serious. The following information is logged in the alert log file:

Internal errors (ORA-600) and block corruption errors (ORA-1578 or ORA-1498) Operations that effect database structures and parameters and statements such as CREATE DATABASE, STARTUP, SHUTDOWN, ARCHIVE LOG, and RECOVER The values of all nondefault initialization parameters at the time of instance starts Checkpoint start and end times Incomplete checkpoints Time to perform archiving Crash recovery start and complete times

Question 37: Which parameter shows the location of ALERT.LOG file? The location of the ALERT.LOG file is given BACKGROUND_DUMP_DEST

by

the

parameter

Question 38: What parameter is used to log checkpointing start and end time in alert.log file? If the LOG_CHECKPOINTS_TO_ALERT parameter has been set to true.

Вам также может понравиться