Showing posts with label SQL AND PL SQL. Show all posts
Showing posts with label SQL AND PL SQL. Show all posts

Saturday, May 9, 2015

SQL-MULTIPLE INSERTS



MULTIPLE INSERTS

We have table called DEPT with the following columns and data

DEPTNO         DNAME           LOC
--------            --------            ----
10                    accounting    new york
20                    research        dallas
30                    sales               Chicago
40                    operations    boston

a) CREATE STUDENT TABLE

     SQL> Create table student(no number(2),name varchar(2),marks number(3));

b) MULTI INSERT WITH ALL FIELDS

     SQL> Insert all
             Into student values(1,’a’,100)
             Into student values(2,’b’,200)
             Into student values(3,’c’,300)
             Select *from dept where deptno=10;

     -- This inserts 3 rows

c) MULTI INSERT WITH SPECIFIED FIELDS

     SQL> insert all
             Into student (no,name) values(4,’d’)
             Into student(name,marks) values(’e’,400)
             Into student values(3,’c’,300)
             Select *from dept where deptno=10;

     -- This inserts 3 rows

d) MULTI INSERT WITH DUPLICATE ROWS

     SQL> insert all
             Into student values(1,’a’,100)
             Into student values(2,’b’,200)
             Into student values(3,’c’,300)
             Select *from dept where deptno > 10;

     -- This inserts 9 rows because in the select statement retrieves 3 records (3 inserts for
         each row retrieved)

e) MULTI INSERT WITH CONDITIONS BASED

     SQL> Insert all
             When deptno > 10 then
             Into student1 values(1,’a’,100)
             When dname = ‘SALES’ then
             Into student2 values(2,’b’,200)
             When loc = ‘NEW YORK’ then
             Into student3 values(3,’c’,300)
             Select *from dept where deptno>10;

     -- This  inserts 4 rows because the first condition satisfied 3 times, second condition
         satisfied once and the last none.

f) MULTI INSERT WITH CONDITIONS BASED AND ELSE

    SQL> Insert all
            When deptno > 100 then
            Into student1 values(1,’a’,100)
            When dname = ‘S’ then
            Into student2 values(2,’b’,200)
            When loc = ‘NEW YORK’ then
            Into student3 values(3,’c’,300)
            Else
            Into student values(4,’d’,400)
            Select *from dept where deptno>10;

     -- This inserts 3 records because the else satisfied 3 times

g) MULTI INSERT WITH CONDITIONS BASED AND FIRST

     SQL> Insert first
             When deptno = 20 then
             Into student1 values(1,’a’,100)
             When dname = ‘RESEARCH’ then
             Into student2 values(2,’b’,200)
             When loc = ‘NEW YORK’ then
             Into student3 values(3,’c’,300)
             Select *from dept where deptno=20;
   
     -- This inserts 1 record because the first clause avoid to check the remaining
         conditions once the condition is satisfied.

h) MULTI INSERT WITH CONDITIONS BASED, FIRST AND ELSE

     SQL> Insert first
             When deptno = 30 then
              Into student1 values(1,’a’,100)
              When dname = ‘R’ then
              Into student2 values(2,’b’,200)
              When loc = ‘NEW YORK’ then
              Into student3 values(3,’c’,300)
              Else
              Into student values(4,’d’,400)
              Select *from dept where deptno=20;

     -- This inserts 1 record because the else clause satisfied once




i) MULTI INSERT WITH MULTIBLE TABLES

    SQL> Insert all
            Into student1 values(1,’a’,100)
            Into student2 values(2,’b’,200)
            Into student3 values(3,’c’,300)
            Select *from dept where deptno=10;

    -- This inserts 3 rows

    ** You can use multi tables with specified fields, with duplicate rows, with conditions,
         with first and else clauses.

SQL-FUNCTIONS1(DATE FUNCTIONS)


DATE FUNCTIONS

  Sysdate
  Current_date
  Current_timestamp
  Systimestamp
  Localtimestamp
  Dbtimezone
  Sessiontimezone
  To_char
  To_date
  Add_months
  Months_between
  Next_day
  Last_day
  Extract
  Greatest
  Least
  Round
  Trunc
  New_time
 Coalesce

Oracle default date format is DD-MON-YY.
We can change the default format to our desired format by using the following command.

SQL> alter session set nls_date_format = ‘DD-MONTH-YYYY’;
        But this will expire once the session was closed.

a) SYSDATE

     This will give the current date and time.
      Ex:
           SQL> select sysdate from dual;

SYSDATE
-----------
24-DEC-06

b) CURRENT_DATE

     This will returns the current date in the session’s timezone.

      Ex:
           SQL> select current_date from dual;

CURRENT_DATE
------------------
     24-DEC-06

c) CURRENT_TIMESTAMP

     This will returns the current timestamp with the active time zone information.

      Ex:
           SQL> select current_timestamp from dual;

CURRENT_TIMESTAMP
---------------------------------------------------------------------------
24-DEC-06 03.42.41.383369 AM +05:30


d) SYSTIMESTAMP

     This will returns the system date, including fractional seconds and time zone of the
      database.

      Ex:
           SQL> select systimestamp from dual;
SYSTIMESTAMP
---------------------------------------------------------------------------
24-DEC-06 03.49.31.830099 AM +05:30

e) LOCALTIMESTAMP

     This will returns local timestamp in the active time zone information, with no time
     zone information shown.

      Ex:
                   SQL> select localtimestamp from dual;

LOCALTIMESTAMP
---------------------------------------------------------------------------
24-DEC-06 03.44.18.502874 AM


f) DBTIMEZONE

    This will returns the current database time zone in UTC format. (Coordinated Universal
    Time)

    Ex:
                   SQL> select dbtimezone from dual;

DBTIMEZONE
---------------
   -07:00

g) SESSIONTIMEZONE

    This will returns the value of the current session’s time zone.

    Ex:
         SQL> select sessiontimezone from dual;

SESSIONTIMEZONE
------------------------------------
+05:30

     
       h) TO_CHAR

    This will be used to extract various date formats.
    The available date formats as follows.

    Syntax: to_char (date, format)
 
    DATE FORMATS
 
            D                      --         No of days in week
            DD                    --         No of days in month
            DDD                 --         No of days in year
            MM                   --         No of month
            MON                 --         Three letter abbreviation of month
            MONTH             --         Fully spelled out month
            RM                   --         Roman numeral month
            DY                    --         Three letter abbreviated day
            DAY                  --         Fully spelled out day
            Y                      --         Last one digit of the year
            YY                    --         Last two digits of the year
            YYY                  --         Last three digits of the year
            YYYY                --         Full four digit year
            SYYYY             --          Signed year
            I                       --         One digit year from ISO standard
            IY                     --         Two digit year from ISO standard
            IYY                   --         Three digit year from ISO standard
            IYYY                 --         Four digit year from ISO standard
            Y, YYY              --         Year with comma
            YEAR                --         Fully spelled out year
            CC                    --         Century
            Q                      --         No of quarters
            W                     --         No of weeks in month
            WW                  --         No of weeks in year
            IW                    --         No of weeks in year from ISO standard
            HH                    --         Hours
            MI                    --         Minutes
            SS                    --         Seconds
            FF                     --         Fractional seconds
            AM or PM         --         Displays AM or PM depending upon time of day
            A.M or P.M       --         Displays A.M or P.M depending upon time of day
            AD or BC          --         Displays AD or BC depending upon the date
            A.D or B.C        --         Displays AD or BC depending upon the date
            FM                    --         Prefix to month or day, suppresses padding of month or day
            TH                    --         Suffix to a number
            SP                    --         suffix to a number to be spelled out
            SPTH                --         Suffix combination of TH and SP to be both spelled out
            THSP                --         same as SPTH

Ex:
    SQL> select to_char(sysdate,'dd month yyyy hh:mi:ss am dy') from dual;

TO_CHAR(SYSDATE,'DD MONTH YYYYHH:MI
----------------------------------------------------
24 december  2006 02:03:23 pm sun  

    SQL> select to_char(sysdate,'dd month year') from dual;


TO_CHAR(SYSDATE,'DDMONTHYEAR')
-------------------------------------------------------
24 december  two thousand six

     SQL> select to_char(sysdate,'dd fmmonth year') from dual;

TO_CHAR(SYSDATE,'DD FMMONTH YEAR')
-------------------------------------------------------
24 december two thousand six

     SQL> select to_char(sysdate,'ddth DDTH') from dual;

TO_CHAR(S
------------
24th 24TH

     SQL> select to_char(sysdate,'ddspth DDSPTH') from dual;

TO_CHAR(SYSDATE,'DDSPTHDDSPTH
------------------------------------------
twenty-fourth TWENTY-FOURTH

     SQL> select to_char(sysdate,'ddsp Ddsp DDSP ') from dual;

TO_CHAR(SYSDATE,'DDSPDDSPDDSP')
------------------------------------------------
twenty-four Twenty-Four TWENTY-FOUR

i) TO_DATE

    This will be used to convert the string into data format.

    Syntax: to_date (date)

    Ex:
         SQL> select to_char(to_date('24/dec/2006','dd/mon/yyyy'), 'dd * month * day')
                 from dual;

TO_CHAR(TO_DATE('24/DEC/20
--------------------------
24 * december  * Sunday

-- If you are not using to_char oracle will display output in default date format.
     
j) ADD_MONTHS

    This will add the specified months to the given date.

    Syntax: add_months (date, no_of_months)

    Ex:
          SQL> select add_months(to_date('11-jan-1990','dd-mon-yyyy'), 5) from dual;

ADD_MONTHS
----------------
11-JUN-90

SQL> select add_months(to_date('11-jan-1990','dd-mon-yyyy'), -5) from dual;

ADD_MONTH
---------------
11-AUG-89        

Ø  If no_of_months is zero then it will display the same date.
Ø  If no_of_months is null then it will display nothing.

k) MONTHS_BETWEEN

    This will give difference of months between two dates.

    Syntax: months_between (date1, date2)

    Ex:
         SQL> select months_between(to_date('11-aug-1990','dd-mon-yyyy'), to_date('11-
                 jan-1990','dd-mon-yyyy')) from dual;



MONTHS_BETWEEN(TO_DATE('11-AUG-1990','DD-MON-YYYY'),TO_DATE('11-JAN-1990','DD-MON-YYYY'))
-----------------------------------------------------------------------------------------------
                                                                                        7
           SQL> select months_between(to_date('11-jan-1990','dd-mon-yyyy'), to_date('11-
                 aug-1990','dd-mon-yyyy')) from dual;

MONTHS_BETWEEN(TO_DATE('11-JAN-1990','DD-MON-YYYY'),TO_DATE('11-AUG-1990','DD-MON-YYYY'))
-------------------------------------------------------------------------------------------------
                                                                                       -7

l) NEXT_DAY
               
    This will produce next day of the given day from the specified date.

    Syntax: next_day (date,  day)

    Ex:
         SQL> select next_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun') from dual;

NEXT_DAY(
-------------
31-DEC-06

-- If the day parameter is null then it will display nothing.

m) LAST_DAY

    This will produce last day of the given date.

    Syntax: last_day (date)

    Ex:
         SQL> select last_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun') from dual;
LAST_DAY(
-------------
31-DEC-06

n) EXTRACT

    This is used to extract a portion of the date value.

    Syntax: extract ((year | month | day | hour | minute | second), date)

    Ex:
         SQL> select extract(year from sysdate) from dual;
EXTRACT(YEARFROMSYSDATE)
------------------------------------
                    2006

-- You can extract only one value at a time.

o) GREATEST

     This will give the greatest date.

     Syntax: greatest (date1, date2, date3 … daten)

     Ex:
         SQL> select greatest(to_date('11-jan-90','dd-mon-yy'),to_date('11-mar-90','dd-
                 mon-yy'),to_date('11-apr-90','dd-mon-yy')) from dual;

  GREATEST(
  -------------
   11-APR-90

p) LEAST

     This will give the least date.
     Syntax: least (date1, date2, date3 … daten)

     Ex:
         SQL> select least(to_date('11-jan-90','dd-mon-yy'),to_date('11-mar-90','dd-mon-
                 yy'),to_date('11-apr-90','dd-mon-yy')) from dual;

  LEAST(
  -------------
   11-JAN-90

q) ROUND

    Round will rounds the date to which it was equal to or greater than the given date.

    Syntax: round (date, (day | month | year))

    If the second parameter was year then round will checks the month of the given date in
    the following ranges.

JAN      --          JUN  
            JUL       --          DEC

    If the month falls between JAN and JUN then it returns the first day of the current year.
    If the month falls between JUL and DEC then it returns the first day of the next year.

    If the second parameter was month then round will checks the day of the given date in
    the following ranges.

            1          --         15    
            16        --         31

    If the day falls between 1 and 15 then it returns the first day of the current month.
    If the day falls between 16 and 31 then it returns the first day of the next month.

    If the second parameter was day then round will checks the week day of the given date
    in the following ranges.

            SUN      --          WED
            THU      --          SUN

    If the week day falls between SUN and WED then it returns the previous sunday.
    If the weekday falls between THU and SUN then it returns the next sunday.

Ø  If the second parameter was null then it returns nothing.
Ø  If the you are not specifying the second parameter then round will resets the time to the begining of the current day in case of user specified date.
Ø  If the you are not specifying the second parameter then round will resets the time to the begining of the next day in case of sysdate.

    Ex:
         SQL> select round(to_date('24-dec-04','dd-mon-yy'),'year'), round(to_date('11-mar-
                 06','dd-mon-yy'),'year') from dual;

ROUND(TO_ ROUND(TO_
------------   ---------------
01-JAN-05   01-JAN-06

           SQL> select round(to_date('11-jan-04','dd-mon-yy'),'month'), round(to_date('18-
                 jan-04','dd-mon-yy'),'month') from dual;

ROUND(TO_ ROUND(TO_
-------------  ---------------
01-JAN-04    01-FEB-04

           SQL> select round(to_date('26-dec-06','dd-mon-yy'),'day'), round(to_date('29-dec-
                 06','dd-mon-yy'),'day') from dual;

ROUND(TO_ ROUND(TO_
--------------  --------------
24-DEC-06     31-DEC-06

           SQL> select to_char(round(to_date('24-dec-06','dd-mon-yy')), 'dd mon yyyy
                 hh:mi:ss am') from dual;
TO_CHAR(ROUND(TO_DATE('
---------------------------------
24 dec 2006 12:00:00 am
r) TRUNC

    Trunc will chops off the date to which it was equal to or less than the given date.

    Syntax: trunc (date, (day | month | year))

  If the second parameter was year then it always returns the first day of the current year.
  If the second parameter was month then it always returns the first day of the current month.
  If the second parameter was day then it always returns the previous sunday.
  If the second parameter was null then it returns nothing.
  If the you are not specifying the second parameter then trunk will resets the time to the begining of the current day.

    Ex:
         SQL> select trunc(to_date('24-dec-04','dd-mon-yy'),'year'), trunc(to_date('11-mar-
                 06','dd-mon-yy'),'year') from dual;

TRUNC(TO_ TRUNC(TO_
-------------  --------------
01-JAN-04    01-JAN-06

                     SQL> select trunc(to_date('11-jan-04','dd-mon-yy'),'month'), trunc(to_date('18-jan-
                         04','dd-mon-yy'),'month') from dual;

TRUNC(TO_ TRUNC(TO_
-------------  -------------
01-JAN-04    01-JAN-04

  SQL> select trunc(to_date('26-dec-06','dd-mon-yy'),'day'), trunc(to_date('29-dec-
          06','dd-mon-yy'),'day') from dual;
                        TRUNC(TO_ TRUNC(TO_
-------------  --------------
24-DEC-06 24-DEC-06
       
          SQL> select to_char(trunc(to_date('24-dec-06','dd-mon-yy')), 'dd mon yyyy hh:mi:ss
                 am') from dual;

TO_CHAR(TRUNC(TO_DATE('
---------------------------------
24 dec 2006 12:00:00 am

s) NEW_TIME

     This will give the desired timezone’s date and time.

     Syntax: new_time (date, current_timezone, desired_timezone)

     Available timezones are as follows.

    TIMEZONES

                        AST/ADT         --         Atlantic standard/day light time
                        BST/BDT          --         Bering standard/day light time
                        CST/CDT          --         Central standard/day light time
                        EST/EDT          --         Eastern standard/day light time
                        GMT                --         Greenwich mean time
                        HST/HDT         --         Alaska-Hawaii standard/day light time
                        MST/MDT         --         Mountain standard/day light time
                        NST                 --          Newfoundland standard time
                        PST/PDT          --         Pacific standard/day light time
                        YST/YDT          --         Yukon standard/day light time

    Ex:
        SQL> select to_char(new_time(sysdate,'gmt','yst'),'dd mon yyyy hh:mi:ss am') from
                dual;

TO_CHAR(NEW_TIME(SYSDAT
-----------------------------------
24 dec 2006 02:51:20 pm

          SQL> select to_char(new_time(sysdate,'gmt','est'),'dd mon yyyy hh:mi:ss am') from
                dual;

TO_CHAR(NEW_TIME(SYSDAT
-----------------------
24 dec 2006 06:51:26 pm

t) COALESCE

    This will give the first non-null date.

    Syntax: coalesce (date1, date2, date3 … daten)

    Ex:
         SQL> select coalesce('12-jan-90','13-jan-99'), coalesce(null,'12-jan-90','23-mar-
                 98',null) from dual;

COALESCE( COALESCE(
-------------  ------------
12-jan-90     12-jan-90

Saturday, December 20, 2014

FAQ’s in SQL & PL/SQL



What is PL/SQL?
PL/SQL is a procedural language that has both interactive SQL and procedural programming language constructs such as iteration, conditional branching.

What are the components of a PL/SQL Block?
Declarative part
Executable part
Exception part

What are the datatypes a available in PL/SQL?
Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN. Some composite data types such as RECORD & TABLE.

What are % TYPE and % ROWTYPE? What are the advantages of using these over datatypes?
% TYPE provides the data type of a variable or a database column to that variable.
% ROWTYPE provides the record type that represents a entire row of a table or view or columns selected in the cursor.
The advantages are:
I. Need not know about variable’s data type
ii. If the database definition of a column in a table changes, the data type of a variable changes accordingly.

What is difference between % ROWTYPE and TYPE RECORD?
% ROWTYPE is to be used whenever query returns an entire row of a table or view. TYPE RECORD is to be used whenever query returns columns of different table or views and variables.

Explain the two types of Cursors?
There are two types of cursors, Implicit Cursor and Explicit Cursor.
PL/SQL uses Implicit Cursors for queries.
User defined cursors are called Explicit Cursors. They can be declared and used.

What are the cursor attributes used in PL/SQL?
% ISOPEN – Used to check whether a cursor is open or not.
% ROWCOUNT – Used to check the number of rows fetched/updated/deleted.
% FOUND – Used to check whether cursor has fetched any row. True if rows are fetched.
% NOT FOUND – Used to check whether cursor has fetched any row. True if no rows are fetched.

What is a cursor for loop?
Cursor for loop implicitly declares %ROWTYPE as loop index, opens a cursor, fetches rows of values from active set into fields in the record and closes when all the records have been processed.

What is the difference between implicit and explicit cursors?
An explicit cursor is declared opened and fetched from in the program block where as an implicit cursor is automatically generated for SQL statements that process a single row only.

What are the different types of joins available in Oracle?
Equi Join: When primary and foreign key relationship exists between the tables that are going to be joined.
Self Join: If comparison comes in a single table
Cartesian Join: When tables are joined without giving any join condition.
Inner Join: The resultant set includes all the rows that satisfy the join condition.
Outer Join: The resultant set includes the rows which doesn’t satisfy the join condition.  The outer join operator Plus sign (+) will be included in the join condition.

What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?
SQLCODE returns the value of the error number for the last error encountered. The SQLERRM returns the actual error message for the last error encountered. They can be used in exception handling to report, or, store in an error log table, the error that occurred in the code. These are especially useful for the WHEN OTHERS exception.

What is an autonomous transaction?
An autonomous transaction is an independent transaction that is initiated by another transaction (the parent transaction). An autonomous transaction can modify data and commit or rollback independent of the state of the parent transaction.

What is the difference between View and Materialized view?
Materialized view will not be refreshed every time you query the view. So to have good performance when data is not changed so rapidly, we use Materialized views rather than normal views which always fetches data from tables every time you run a query on it.

What is dynamic SQL?
Dynamic SQL allows you to construct a query, a DELETE statement, a CREATE TABLE statement, or even a PL/SQL block as a string and then execute it at runtime.

Can you use COMMIT in a trigger?
Yes but by defining an autonomous transaction.

What is the difference between anonymous blocks and stored procedures?
Anonymous block is compiled only when called. Stored procedure is compiled and stored in database with the dependency information as well. Former is PL/SQL code directly called from an application. Latter is stored in database. Former has declare statement. Latter doesn’t.

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 is Correlated Subquery?
Correlated Subquery is a subquery that is evaluated once for each row processed by the parent statement. Parent statement can be Select, Update or Delete.

What is Sequence?
Sequences are used for generating sequence numbers without any overhead of locking. Drawback is that after generating a sequence number if the transaction is rolled back, then that sequence number is lost.

What is SQL Deadlock?
Deadlock is a unique situation in a multi user system that causes two or more users to wait indefinitely for a locked resource. First user needs a resource locked by the second user and the second user needs a resource locked by the first user. To avoid dead locks, avoid using exclusive table lock and if using, use it in the same sequence and use Commit frequently to release locks.

What is SQL*Loader?
SQL*Loader is a product for moving data in external files into tables in an Oracle database. To load data from external files into an Oracle database, two types of input must be provided to SQL*Loader: the data itself and the control file.

What is the use of CASCADE CONSTRAINTS?
When this clause is used with the DROP command, a parent table can be dropped even when a child table exists.

Explain forward declaration used in functions?
A forward declaration means that modules (procedures and functions) are declared in advance of their actual body definition. This declaration makes that module available to be called by other modules even before the program’s body is defined. A forward declaration consists simply of the module header, which is just the name of the module followed by the parameter list (and a RETURN clause in case the module is a function), no more no less.
Forward declarations are required in one specific situation: mutual recursion.

What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?
SQLCODE returns the value of the error number for the last error encountered. The SQLERRM returns the actual error message for the last error encountered. They can be used in exception handling to report, or, store in an error log table, the error that occurred in the code. These are especially useful for the WHEN OTHERS exception.

What is the difference between Truncate and Delete Commands?

TRUNCATE is a DDL command whereas DELETE is a DML command. Hence DELETE operation can be rolled back, but TRUNCATE operation cannot be rolled back. WHERE clause can be used with DELETE and not with TRUNCATE.

What is the Purpose of HAVING Clause?
The HAVING clause is used in combination with the GROUP BY clause. It can be used in a SELECT statement to filter the records that a GROUP BY returns.

What is INLINE View in SQL?
The inline view is a construct in Oracle SQL where you can place a query in the SQL FROM, clause, just as if the query was a table name.

While creating a sequence, what does cache and nocache options mean?
With respect to a sequence, the cache option specifies how many sequence values will be stored in memory for faster access.

Does the view exist if the table is dropped from the database?
Yes, in Oracle, the view continues to exist even after one of the tables (that the view is based on) is dropped from the database. However, if you try to query the view after the table has been dropped, you will receive a message indicating that the view has errors.

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.

What types of index data structures can you have?
An index helps to faster search values in tables. The three most commonly used index-types are:
§  B-Tree: builds a tree of possible values with a list of row IDs that have the leaf value. Needs a lot of space and is the default index type for most databases.
§  Bitmap: string of bits for each possible value of the column. Each bit string has one bit for each row. Needs only little space and is very fast. (However, domain of value cannot be large, e.g. SEX(m,f); degree(BS,MS,PHD)
§  Hash: A hashing algorithm is used to assign a set of characters to represent a text string such as a composite of keys or partial keys, and compresses the underlying data. Takes longer to build and is supported by relatively few databases.

What is the difference between a “where” clause and a “having” clause?
“Where” is a kind of restriction statement. You use where clause to restrict all the data from DB. Where clause is used before result retrieving. But Having clause is using after retrieving the data. Having clause is a kind of filtering command.

Can a view be updated/inserted/deleted? If Yes – under what conditions?
A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from one or more tables then insert, update and delete is not possible.

What is tkprof and how is it used?
The tkprof tool is a tuning tool used to determine cpu and execution times for SQL statements. You use it by first setting timed_statistics to true in the initialization file and then turning on tracing for either the entire database via the sql_trace parameter or for the session using the ALTER SESSION command. Once the trace file is generated you run the tkprof tool against the trace file and then look at the output from the tkprof tool. This can also be used to generate explain plan output.

What is explain plan and how is it used?
The EXPLAIN PLAN command is a tool to tune SQL statements. To use it you must have an explain_table generated in the user you are running the explain plan for. This is created using the utlxplan.sql script. Once the explain plan table exists you run the explain plan command giving as its argument the SQL statement to be explained. The explain_plan table is then queried to see the execution plan of the statement. Explain plans can also be run using tkprof.

What are the Lock types?
Share Lock: It allows the other users for only reading not to insert or update or delete.
Exclusive Lock: Only one user can have the privileges of insert or update and delete of particular objectothers can only read.
Update Lock: Multiple user can read, update delete .

What is Pragma EXECPTION_INIT? Explain the usage?

The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle error. 
E.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)

What is Raise_application_error?
Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue a user_defined error messages from stored sub-program or database trigger.

What are the modes for passing parameters to Oracle?
There are three modes for passing parameters to subprograms
IN – An In-parameter lets you pass values to the subprogram being called. In the subprogram it acts like a constant and cannot be assigned a value.
OUT – An out-parameter lets you return values to the caller of the subprogram. It acts like an initialized variable its value cannot be assigned to another variable or to itself.
INOUT – An in-out parameter lets you pass initial values to the subprogram being called and returns updated values to the caller.

What is the difference between Package, Procedure and Functions?
A package is a database objects that logically groups related PL/SQL types, objects, and Subprograms.
Procedure is a sub program written to perform a set of actions and can return multiple values.
Function is a subprogram written to perform certain computations and return a single value.
Unlike subprograms packages cannot be called, passed parameters or nested.

How do you make a Function and Procedure as a Private?
Functions and Procedures can be made private to a package by not mentioning their declaration in the package specification and by just mentioning them in the package body.

What is Commit, Rollback and Save point?
Commit – Makes changes to the current transaction permanent. It erases the savepoints and releases the transaction locks.
Savepoint –Savepoints allow to arbitrarily hold work at any point of time with option of later committing. They are used to divide transactions into smaller portions.
Rollback – This statement is used to undo work.

What is the difference between DDL, DML and DCL structures?
DDL statements are used for defining data. Ex: Create, Alter, Drop, Truncate, Rename.
DML statements are used for manipulating data. Ex: Insert, update, truncate.
DCL statements are used for to control the access of data. Ex; Grant, Revoke.
TCL statements are used for data saving. Ex; Commit, Rollback, Savepoint.

What is the difference between the snapshot and synonym?
A snapshot refers to read-only copies of a master table or tables located on a remote node. A snapshot can be queried, but not updated; only the master table can be updated. A snapshot is periodically refreshed to reflect changes made to the master table. In this sense, a snapshot is really a view with periodicity.
A synonym is an alias for table, view, sequence or program unit. They are of two types private and public.

What is the difference between data types char and varchar?
Char reserves the number of memory locations mentioned in the variable declarations, even though not used (it can store a maximum of 255 bytes). Where as Varchar does not reserve any memory locations when the variable is declared, it stores the values only after they are assigned (it can store a maximum of 32767 bytes).

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.

Tell some new features in PL/SQL in 10g?
-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
- 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 Overloading in PL/SQL?
Overloading is an oops concept (Object Oriented Programming). By using the same name we can write any number of Procedures or functions in a package but either number of parameters in the procedure/function must vary or parameter datatype must vary.

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.

What is Nested Table?
A nested table is a table within a table. A nested table is a collection of rows, represented as a column within the main table. For each record within main table, the nested table may contain multiple rows.  In a sense, it’s a way of storing a one-to many relationship within one table.

What is Varying Array?
A varying array is a set of objects, each with the same data types. The size of the array is limited when it is created. (When the table is created with a varying array, the array is a nested table with a limited set of rows). Varying arrays also known as VARRAYS, allows storing repeated attributes in tables.

Give some most often used predefined exceptions?
a) NO_DATA_FOUND (Select Statement returns no rows)
b) TOO_MANY_ROWS (Single row Select statement returns more than 1 row)
c) INVALID_CURSOR (Illegal cursor operations occurred)
d) CURSOR_ALREADY_OPEN (If cursor is opened & we are trying to reopen it)
e) INVALID_NUMBER (Conversion of Character to number fails)
f) ZERO_DIVIDE
g) DUP_VAL_ON_INDEX (Attempted to insert a duplicate value)

Give some important Oracle supplied packages?
DBMS_SQL: It is used to write Procedures & Anonymous blocks that use Dynamic SQL.
DBMS_JOB: Using it, we can submit PL/SQL programs for execution, execute PL/SQL programs on a schedule, identify when programs should run, remove programs from the schedule & suspend programs from running.
DBMS_OUTPUT: This package outputs values & messages from any PL/SQL block.
UTL_FILE: With this package, you can read from & write to Operating system files
UTL_HTTP: This package allows to make HTTP Requests directly from the database.

What is Instead Of Trigger?
This trigger is used to perform DML operation directly on the underlying tables, because a view cannot be modified by normal DML Statements if it contains joins or Group Functions. These triggers are Only Row Level Triggers. The CHECK option for views is not enforced when DML to the view are performed by Instead of Trigger.

What is the Sequence of Firing Database Triggers?
a) Before Row Level Trigger
b) Before Statement Level Trigger
c) After Row Level Trigger
d) Statement Operation
e) After Statement Level Trigger

What is the Difference between PL/SQL Table & Nested Table?
PL/SQL Table: Index by Tables are not Stored in Database.
Nested Table: Nested Tables are Stored in Database as Database Columns.

What is the Difference between Nested Table & Varray?
Nested Table
a) This are Sparse
b) We can Delete its Individual Elements
c) It do not have an Upper Boundary
d) This are Stored in System Generated Table
Varray
a) This are Dense
b) We cannot Delete its Elements
c) This are Fixed Size & always need to specify the size
d) These are Stored in Tablespaces

What are the various SQL Statements?
a) Data Retrieval: Select
b) DML: Insert, Update, Delete
c) DDL: Create, Alter, Drop, Rename, Truncate
d) Transaction Control: Commit, Rollback, Savepoint
e) DCL: Grant, Revoke
f) Session Control: Alter Session, Set Role
g) System Control: Alter System
h) Embedded SQL Statements: Open, Close, Fetch & Execute.
What is Rowid?
It is a Hexadecimal Representation of a Row in a Table. Rowid can only be Changed if we ‘Enable Row Movement’ on a Partitioned Table. Rowid’s of Deleted Rows can be Reused if Transaction is Committed.

What is Partitioning?
It Enables Tables & Indexes or Index-Organized tables to be subdivided into smaller manageable Pieces & these each small Piece is called Partition.
They are of following Types:
a) Range Partitioning
b) Hash Partitioning
c) List Partitioning
d) Composite Range-Hash Partitioning
What is a Cluster?
A cluster provides an optional method of storing table data. A cluster is comprised of a group of tables that share the same data blocks, which are grouped together because they share common columns and are often used together. For example, the EMP and DEPT table share the DEPTNO column. When you cluster the EMP and DEPT, Oracle physically stores all rows for each department from both the EMP and DEPT tables in the same data blocks. You should not use Clusters for tables that are frequently accessed individually.

What is the Difference between Nested Subquery & Correlated Subquery?
Nested Subquery
a) Inner Query runs first and executes once, returning values which are to be used by the Main query or outer query
b) Outer query is driver by Inner Query
Correlated Subquery
a) A Correlated Subquery or Inner Query execute once for each candidate row considered by outer query
b) Inner Query is Driven by Outer Query

What is the Difference between Translate & Replace?
Translate function converts each character in String with specified one whereas Replace function replaces part of the string in continuity by another sub-string.