11
What are Pseudo columns? - They are not actual columns. They are like Functions without arguments. - They typically give a different value for each row. - Examples: ROWNUM, NEXTVAL, ROWID, VERSION_STARTTIME Why use Truncate over Delete while deleting all rows? - Truncate is efficient. Triggers are not fired. - It deallocates space (Unless REUSE STORAGE is given). What is a ROWID composed of ? - It's a hexadecimal string representing the address of a row. Prior to Oracle 8, it's a restricted rowid comprising block.row.file. Extended rowid ( the default on higher releases) comprises data object number as well ( comprising the segment number ). What is the use of a ROWID? - Retrieve data faster with ROWID. - Shows you the physical arrangement of rows in the table. - Also unique identifier for each row. Can rows from two different tables have the same ROWID? - Possible, if they are in a Cluster What is ROWNUM and ROW_NUMBER? - ROWNUM is a pseudocolumn which is the number assigned to each row retrieved. - ROW_NUMBER is an analytic function which does something similar, but has all the capabilities of PARTITION BY and ORDER BY clauses.. What is an inline view? - It's not a schema object - It's a subquery in the FROM clause with an alias that can be used as a view within the SQL statement. What are Nested and Correlated sub queries? - The subquery used in WHERE clause is a nested subquery. - If this subquery refers to any column in the parent statement, it becomes a correlated subquery. How do you retrieve a dropped table in 10g?

PL-SQL

Embed Size (px)

Citation preview

Page 1: PL-SQL

What are Pseudo columns?- They are not actual columns. They are like Functions without arguments.

- They typically give a different value for each row.

- Examples: ROWNUM, NEXTVAL, ROWID, VERSION_STARTTIME

Why use Truncate over Delete while deleting all rows?- Truncate is efficient. Triggers are not fired.

- It deallocates space (Unless REUSE STORAGE is given).

What is a ROWID composed of ?- It's a hexadecimal string representing the address of a row. Prior to Oracle 8, it's a restricted rowid comprising block.row.file. Extended rowid ( the default on higher releases) comprises data object number as well ( comprising the segment number ).

What is the use of a ROWID?- Retrieve data faster with ROWID.

- Shows you the physical arrangement of rows in the table.

- Also unique identifier for each row.

Can rows from two different tables have the same ROWID?- Possible, if they are in a Cluster

What is ROWNUM and ROW_NUMBER?- ROWNUM is a pseudocolumn which is the number assigned to each row retrieved.

- ROW_NUMBER is an analytic function which does something similar, but has all the capabilities of PARTITION BY and ORDER BY clauses..

What is an inline view?- It's not a schema object

- It's a subquery in the FROM clause with an alias that can be used as a view within the SQL statement.

What are Nested and Correlated sub queries?- The subquery used in WHERE clause is a nested subquery.

- If this subquery refers to any column in the parent statement, it becomes a correlated subquery.

How do you retrieve a dropped table in 10g?- FLASHBACK table <tabname> to BEFORE DROP

What is an index-organized table?- The physical arrangement of rows of this table changes with the indexed column.

- It's. in-short, a table stored like an index itself.

Page 2: PL-SQL

What is a mutating table error and how can you get around it?

This happens with triggers. It occurs because the trigger is trying to update a row it is currently using. The usual fix involves either use of views or temporary tables so the database is selecting from one while updating the other.

Describe the use of %ROWTYPE and %TYPE in PL/SQL

%ROWTYPE allows you to associate a variable with an entire table row. The %TYPE associates a variable with a single column type.

escribe the use of PL/SQL tables

PL/SQL tables are scalar arrays that can be referenced by a binary integer. They can be used to hold values for use in later queries or calculations. In Oracle 8 they will be able to be of the %ROWTYPE designation, or RECORD.

In what order should a open/fetch/loop set of commands in a PL/SQL block be implemented if you use the %NOTFOUND cursor variable in the exit when statement? Why?

OPEN then FETCH then LOOP followed by the exit when. If not specified in this order will result in the final return being done twice because of the way the %NOTFOUND is handled by PL/SQL.

What are the types of triggers?

There are 12 types of triggers in PL/SQL that consist of combinations of the BEFORE, AFTER, ROW, TABLE, INSERT, UPDATE, DELETE and ALL key words:

BEFORE ALL ROW INSERT

AFTER ALL ROW INSERT

BEFORE INSERT

AFTER INSERT etc.

Tell some new features in PL/SQL in 10g (Intermediate to Advanced) - Regular expression functions REGEXP_LIKE , REGEXP_INSTR, REGEXP_REPLACE, and REGEXP_SUBSTR- Compile time warnings - Conditional compilation - Improvement to native compilation - BINARY_INTEGER made similar to PLS_INTEGER - INDICES OF , VALUES OF in FORALL lets you work on non-consecutive indices - Quoting mechanism . Instead of quoting single quotes twice everytime, give your own delimiter to go on using single quotes. Ex: q'!I'm a string, you're a string.!' - Flashback Query functions. SCN_TO_TIMESTAMP, TIMESTAMP_TO_SCN 

Page 3: PL-SQL

- Implicit conversion between CLOB and NCLOB - Improved Overloading - New datatypes BINARY_FLOAT, BINARY_DOUBLE - Global optimization enabled - PLS_INTEGER range increased to 32bit - DYNAMIC WRAP using DBMS_DDL

What is a sequence ? - A database object that offers high-speed access to an integer value - Guaranteed to be unique (within that sequence). -Used commonly to generate Primary key values

What is MERGE ? Combination of INSERT and UPDATE

Tell some tips to avoid performance problems in PL/SQL. - Use FORALL instead of FOR, and use BULK COLLECT to avoid looping many times - Tune SQL statements to avoid CPU overhead - Use NOCOPY for OUT and IN OUT if the original value need not be retained. Overhead of keeping a copy of OUT is avoided. - Reorder conditional tests to put least expensive ones first - Minimize datatype conversions => Assign data to exact same type variables- Use PLS_INTEGER for computation intensive code. NUMBER, INTEGER maintain precision and scale but not optimized for performance as additional checks are made to maintain precision and scale. - Do not use subtypes like POSITIVE, NATURAL, INTEGER as they have additional checks - Use BINARY_FLOAT, BINARY_DOUBLE - EXECUTE IMMEDIATE is faster than DBMS_SQL

What are the advantages of Packages ? - Encapsulation of code logic - Privileges to objects can be controlled - Loaded once into memory , used subsequently. - Dependency simplified - Public/private procs, functions, variables

What is a package spec and package body ? Why the separation ? - Spec declares public constructs. Body defines public constructs, additionally declares and defines Private constructs - Separation helps make development easier - Dependency is simplified. You can modify body without invalidating dependent objects.

What are the advantages and disadvantages of DBMS_SQL ? - It has all the advantages of dynamic sql .. like runtime construction of sql, DDL statements can be executed. - Its advantage over EXECUTE IMMEDIATE is it can Describe objects - It's kind of bulky and difficult compared to EXECUTE IMMEDIATE.

Page 4: PL-SQL

Explicit Cursor attributes

There are four cursor attributes used in Oracle

cursor_name%Found, cursor_name%NOTFOUND, cursor_name%ROWCOUNT, cursor_name%ISOPEN

10. Implicit Cursor attributes

Same as explicit cursor but prefixed by the word SQL

SQL%Found, SQL%NOTFOUND, SQL%ROWCOUNT, SQL%ISOPEN

Tips : 1. Here SQL%ISOPEN is false, because oracle automatically closed the implicit cursor after

executing SQL statements.

: 2. All are Boolean attributes.

11. Find out nth highest salary from emp table

SELECT DISTINCT (a.sal) FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT (b.sal)) FROM EMP B

WHERE a.sal<=b.sal);

Enter value for n: 2

SAL

--------- 3700

Any three PL/SQL Exceptions? Too_many_rows, No_Data_Found, Value_Error, Zero_Error, Others

Triggers

nsert Update DeleteBefore Row o.k. o.k. o.k.After Row o.k. o.k. o.k.Before Statement o.k. o.k. o.k.After Statement o.k. o.k. o.k.If FOR EACH ROW clause is specified, then the trigger for each Row affected by the statement.If WHEN clause is specified, the trigger fires according to the returned Boolean value.

Page 5: PL-SQL

Row level trigger,Statement level trigger,Instead of trigger(created on views)

ROWID : Every record in a database is uniquely identified by system generated value called Rowid. It Is a 18 character hexma decimal value. These Rowid's are physically existence.

ROWNUM : It is a pseduocolumn which generates the sequence of numeric values based on the position of the records in the output. These ROWNUM'S logically generated.

NEXTVAL,CURRVAL,SYSDATE,LEVEL ARE PSEDUOCOLUMNS

In pl/sql functions what is use of out parameter even though we have returnstatement.

We can use OUT parameter in functions in order to return values but Return also is a MUST.. Best practice is that if you need multiple values, use procedures instead of functions.

What is Pragma EXECPTION_INIT ? Explain the usage?

The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle error. To get an error message of a specific oracle error.e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)

Cursor Variable Restrictions

u cannot declare cursor in package specification

not allowed when using db links

cannot use comparison operators

cannot assign NULL

cursor's values cannot be stored in table columns

cannot be used with associative array, nested tables and varray

cannot be use one where the other is expected

cannot reference a cursor variable in cursor FOR LOOP

cannot direclty goto any columns

Reference Cursors

Ref Cursor is cursor variable. It is a pointer to a result set. It is useful in scenarios when result set is created in one program and the processing of the same in some other, might be written in different

Page 6: PL-SQL

language, e.g. firing the select is done in PL/SQL and the processing will be done in Java.

Ref cursors are used when we want to use the cursor which is not bound to a specific query.Cursor variables can be tied to many such type of compatible queries.

What is difference between a Cursor declared in a procedure and Cursor declared in a package specification?

A cursor declared in a package specification is global and can be accessed by other procedures or procedures in a package.A cursor declared in a procedure is local to the procedure that can not be accessed by other procedures

What is difference between % ROWTYPE and TYPE RECORD ?

% ROWTYPE is to be used whenever query returns a entire row of a table or view.TYPE rec RECORD is to be used whenever query returns columns of differenttable or views and variables.E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type);e_rec emp% ROWTYPEcursor c1 is select empno,deptno from emp;e_rec c1 %ROWTYPE.

What are % TYPE and % ROWTYPE ? What are the advantages of using these over datatypes?

% TYPE provides the data type of a variable or a database column to that variable.% ROWTYPE provides the record type that represents a entire row of a table or view or columns selected in the cursor.The advantages are : I. Need not know about variable's data typeii. If the database definition of a column in a table changes, the data type of a variable changes accordingly.

What is PL/SQL table ?

PL/SQL tables are PL/SQL?s way of providing arrays. Arrays are like tem-porarytables in memory and thus are processed very quickly. It is impor-tantfor you to realize that they are not database tables, and DMLstatements cannot be issued against them. This type of table is indexedby a binary integer counter (it cannot be indexed by another type ofnumber) whose value can be referenced using the number of the index.Remember that PL/SQL tables exist in memory only, and therefore don?texist in any persistent way, disappearing after the session ends.A PL/SQL TABLE DECLARATIONThere are two steps in the declaration of a PL/SQL table. First, you mustdefine the table structure using the TYPE statement. Second, once a tabletype is created, you then declare the actual table.

FOR EXAMPLEDECLARE

Page 7: PL-SQL

-- Table structure definitionTYPE NameType IS TABLE OFCustomer.name_name%TYPEINDEX BY BINARY_INTEGER;-- Create the actual tableCnameTab NameType;KnameTab NameType;BEGINNULL; -- ...END;

What is COMPUTE?

When we are trying to determine the sum of some columns in a result set we can use Compute. This function is used for reporting purpose.

Select timestamps, owner, obj_name, action_name from dba_audit_trail;this statement gives last executed time for procedure , function & package.

Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database Trigger? Why?

we cannot use commit and rollback in triggers without using PRAGMA AUTONOMOUS_TRANSACTION.triggers are fired when any DML is performed on a table like insert update or delete, and these all have tendency to lock the rows for their operation. whereas Commit or Rollback when used releases the locks if any acquired by transaction. thus in this state trigger gets confused either to lock the rows or to release the lock and goes to mutating stage.with use of autonomous_transaction parent transaction is seprated from child transaction and child transaction can be committed or rolled back without affecting parent transaction and that is how we can commit or rollback in triggers.

LOCKS

Data Locks protects data i.e. Table or Row lock.Dictionary Locks protects the structure of database object i.e. ensures table's structure does not change for the duration of the transaction.Internal Locks & Latches protects the internal database structures. They are automatic.Exclusive Lock allows queries on locked table but no other activity is allowed.Share Lock allows concurrent queries but prohibits updates to the lockedtables.Row Share allows concurrent access to the locked table but prohibits for a exclusive table lock.Row Exclusive same as Row Share but prohibits locking in shared mode.Shared Row Exclusive locks the whole table and allows users to look at rows in the table but prohibit others from locking the table in share or updating them.Share Update are synonymous with Row Share.

Page 8: PL-SQL